Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select(), recv() and EWOULDBLOCK on non-blocking sockets

Tags:

c++

c

sockets

I would like to know if the following scenario is real?!

  1. select() (RD) on non-blocking TCP socket says that the socket is ready
  2. following recv() would return EWOULDBLOCK despite the call to select()
like image 746
tonymontana Avatar asked May 26 '09 16:05

tonymontana


People also ask

Is recv () a blocking call?

recv(IPC, Buffer, int n) is a blocking call, that is, if data is available it writes it to the buffer and immediately returns true, and if no data is available it waits for at least n seconds to receive any data.

Why is RECV not blocked?

recv will block until the entire buffer is filled, or the socket is closed. If you want to read length bytes and return, then you must only pass to recv a buffer of size length . This can avoid recv from blocking.

Why is recv blocking?

If a datagram packet is too long to fit in the supplied buffer, datagram sockets discard excess bytes. If data is not available for the socket socket, and socket is in blocking mode, the recv() call blocks the caller until data arrives.

How do I make a TCP socket non-blocking?

To mark a socket as non-blocking, we use the fcntl system call. Here's an example: int flags = guard(fcntl(socket_fd, F_GETFL), "could not get file flags"); guard(fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK), "could not set file flags"); Here's a complete example.


2 Answers

It's possible, but only in a situation where you have multiple threads/processes trying to read from the same socket.

like image 190
Harper Shelby Avatar answered Oct 19 '22 18:10

Harper Shelby


For recv() you would get EAGAIN rather than EWOULDBLOCK, and yes it is possible. Since you have just checked with select() then one of two things happened:

  • Something else (another thread) has drained the input buffer between select() and recv().
  • A receive timeout was set on the socket and it expired without data being received.
like image 6
dwc Avatar answered Oct 19 '22 18:10

dwc