Skip to content
Advertisement

Unexpected behaviour of SO_SNDTIMEO and SO_RCVTIMEO

I’m trying to set the timeout for the blocking TCP socket on Linux using setsockopt with SO_SNDTIMEO and SO_RCVTIMEO. But for some reason I get a lock while waiting on recv call.

Consider the minimal example. I’ve shortened it a bit for readability, the full code is available in this gist. I create a server socket and set the timeouts using setsockopt. Next, the server exchanges messages with the client. After a while, the client interrupts data exchange and closes the socket. But the server still waiting in blocking recv. However, I expect it to abort recv when the timeout expires.

Network functions used by the client and server:

JavaScript

Server:

JavaScript

Client:

JavaScript

What could be wrong?

Is it possible to implement the timeout for recv in this way, without using select, poll and signals?

Thanks!

Advertisement

Answer

You are looping your reading:

JavaScript

yet read from man read returns:

JavaScript

So you are just looping endlessly.

You should correctly handle errno in your program. when SNDTIMEO stuff timeouts, you get: the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK, or EINPROGRESS (for connect(2)) ....

Still EAGAIN can be returned when signal interrupts, so just the usual select() or poll() for 3 seconds would be probably simpler. If not, measure time yourself anyway and set the timeout to the max timeout you want and measure how much time has passed. Along:

JavaScript

Use tools like strace and a debugger to debug your programs.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement