Avoid send to block when not using O_NONBLOCK Avoid send to block when not using O_NONBLOCK unix unix

Avoid send to block when not using O_NONBLOCK


You could use setsockopt() together with SO_SNDTIMEO to set up a maximum amount of time send() will try to do its work.

See man setsockoptand man 7 socket for details.


It might be horrible. If you don't go NONBLOCK-ing mode and calling select(), which internally puts the process on sleep for specific timeout value. That means, fd will be blocked for that specific time period.


This approach actually works but i recently found by reading the man of send that it can blocks if the socket buffer is full and is the flag O_NONBLOCK is not set on the socket.

This is why you use select, but it still isn't reliable, as man select states:

Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.