tags:

views:

383

answers:

2

Hello

How can I try to read data from socket with timeout? I know, select, pselect, poll, has a timeout field, but using of them disables "tcp fast-path" in tcp reno stack.

The only idea I have is to use recv(fd, ..., MSG_DONTWAIT) in a loop

+2  A: 

Install a handler for SIGALRM, then use alarm() or ualarm() before a regular blocking recv(). If the alarm goes off, the recv() will return an error with errno set to EINTR.

caf
alarms (and signals) are the wrong way to this task. If I want to use tcp fast path, than I need minimal latency. Signals are slow.
osgx
+5  A: 

You can use the setsockopt function to set a timeout on receive operations:

SO_RCVTIMEO

Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.

struct timeval tv;

tv.tv_sec = 30;  /* 30 Secs Timeout */
tv.tv_usec = 0;  // Not init'ing this can cause strange errors

setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));
Robert S. Barnes
Will it work for linux 2.6 tcp? udp?
osgx
Yes it will. Thanks a lot
osgx