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.

Asked By: justin

||

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 or select(2), poll(2), or epoll(7) return a readability event because the connection might have been removed by an asynchronous network error or another thread before accept() is called. If this happens, then the call will block waiting for the next connection to arrive. To ensure that accept() never blocks, the passed socket sockfd needs to have the O_NONBLOCK flag set (see socket(7)).

Answered By: ctrl-d
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.