I am using the select() polling function to determine when there is data to be read from a socket. I am doing this so that I do not have to rely on blocking functions like accept() and recv(). Since select() blocks until the file handle has data, is it necessary to set the sockets to non-blocking using fcntl()?
It seems to me that it is not necessary, since the select() function tells me that data is ready to be read from the socket file handle.
I have seen code in which the programmer has used select() and has also set sockets to non-blocking, and I have seen code in which the programmer has used select and has left the blocking settings in place. Which is correct? Is there an advantage to using select() and setting sockets to non-blocking?
Yes, you should in general set the sockets to non-blocking. Here's why:
When writing to sockets, the fact that you can write to the socket does not necessarily mean you can write all you want to the socket without blocking. Hence a write to a socket might block if you have a large amount of data to write to the socket, but the socket buffer only has space for a smaller amount.
When reading from sockets, the fact there is data to be read from the socket does not necessarily mean there will be all the data there that you want (though it will return a short read if you do).
If you are only writing or reading one byte at a time, I suppose that would be an exception, but it is a rare exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With