non-blocking socket with a timeout
I was trying to read other threads before I submit a duplicate, but I think I have some conceptual problem about setting non-blocking sockets with timeouts.
Basically, what I want to do is setup a socket that if the send/receive wait for 10 seconds, they will move on (do other important stuff).
That said, I realized that I need a non-blocking socket. This is the code (in snippets) that I have so far but I am not seeing what I think I should.
After this point, I expect the socket to wait until it receives a packet for 10 seconds before it barfs...
/* set timeouts for send/receive on this socket */
tv.tv_sec = 10; /* seconds */
tv.tv_usec = 0;
opt = 1;
/* Hard coded for now */
port_num = 5432;
/* Create our socket */
main_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
/* Set it up with an address */
memset(&sock_info, 0, sizeof(struct sockaddr_in));
sock_info.sin_family = AF_INET;
sock_info.sin_port = htons((unsigned short)port_num);
sock_info.sin_addr.s_addr = htonl(INADDR_ANY);
status = bind(main_socket, &sock_info, sizeof(struct sockaddr_in));
/* listen for connection requests */
status = listen(main_socket, 1); /* set to only one connection */
/* Wait until we get one */
accept_socket = -1;
accept_socket = accept(main_socket, &client_info, &info_len);
if (accept_socket > 0)
ioctl(accept_socket, FIONBIO, &opt);
if(setsockopt(accept_socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0)
printf("Cannot Set SO_SNDTIMEO for socket\n");
if(setsockopt(accept_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
printf("Cannot Set SO_RCVTIMEO for socket\n");
but it takes less than a second to quit on me...
rcv_len = recv(accept_socket, my_message, MSG_SIZE, 0);
if( rcv_len < 0)
else if(rcv_len >= 0)
By the way, I know that some might recommend
fcntl( accept_socket, O_NONBLOCK, 0 );
over what I have, but I am required to use the method I included in the code.
Can anyone shed some light on my senario?
thanks in advance.