Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I use select() polling method, should I set sockets to non-blocking?

Tags:

c

tcp

sockets

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?

like image 822
Stephen305 Avatar asked Sep 20 '15 19:09

Stephen305


1 Answers

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.

like image 81
abligh Avatar answered Oct 20 '22 08:10

abligh