select() marks a FD to be readable, but there is no data to be read
I’m encountering an issue in my server code where calling accept()
on the listening socket will occasionally block, even though select()
marked it readable. My understanding is that this isn’t a case that should happen often, if at all, but I’m not sure if there is a POSIX-standard guarantee on data being available when a socket is "readable". I am currently investigating my code logic for error, but was wondering if anyone had experience with this kind of issue and know what kind of scenarios would need to happen for this situation to arise? Thank you.
This is correct behaviour. You cannot be sure that a connection still sits on the accept-queue if you do an accept()
after a select()
since the connection can already be terminated by the initiator or taken by another accepting process. From man 2 accept
:
There may not always be a connection waiting after a
SIGIO
is delivered orselect(2)
,poll(2)
, orepoll(7)
return a readability event because the connection might have been removed by an asynchronous network error or another thread beforeaccept()
is called. If this happens, then the call will block waiting for the next connection to arrive. To ensure thataccept()
never blocks, the passed socketsockfd
needs to have theO_NONBLOCK
flag set (seesocket(7)
).