Question

I'm setting a timeout for the socket using SO_RCVTIMEO to 10 seconds. This question is specific to a stream socket (TCP). When I call recv(...) from what I can gather from the man pages, here is what I'm expecting:

  1. If remote closes the connection, it returns 0 immediately regardless of the timeout.
  2. If the timeout expires and no data was received, then we get a -1 returned and an errno of EAGAIN or EWOULDBLOCK.
  3. If an error occurs on the socket, it returns immediately with a -1 and then errno is set properly.
  4. If data becomes available, the socket waits until the timeout occurs before returning. This time it'll return in 10 seconds with the total bytes received.

Is this the correct behavior? I just want to make sure I'm properly understanding the docs.

Thanks! Brett

Was it helpful?

Solution

  1. Correct.
  2. There are two different specifications (unfortunately I cannot test currently)
    2.1 ETIMEOUT would be returned. (EAGAIN or EWOULDBLOCK are returned on non-blocking sockets if no data is immediately available.) http://pubs.opengroup.org/onlinepubs/9699919799/functions/recv.html
    2.2 EAGAIN or EWOULDBLOCK would be returned for both possibilities mentioned under 2.1 http://man7.org/linux/man-pages/man2/recvmsg.2.html
  3. Correct.
  4. If at least 1 byte was read the socket might return anytime, even if less was read then told and the time-out did not yet expire.

OTHER TIPS

Pretty much.

There is one caveat: if you set MSG_WAITALL, at least one implementation (FreeBSD) starts the timer over again every time some data arrive. For instance, if you ask to recv 8192 bytes and one byte arrives, the timer is reset. If another byte arrives within 10 seconds, the timer resets again. So if bytes trickle in one every 5 seconds, you'll wait (8191 * 5) = 40955 seconds = over 11 hours before recv finally returns 8192. (If not enough bytes arrive before EOF the recv fails with EAGAIN.)

The documentation implied (to me at least) that this occurred even without MSG_WAITALL, but testing demonstrates that this caveat applies only to the MSG_WAITALL case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top