Is it possible (and safe) to make an accepting socket non-blocking?
No idea about Windows, but the behavior you want is guaranteed by POSIX:
If the listen queue is empty of connection requests and O_NONBLOCK is not set on the file descriptor for the socket, accept() shall block until a connection is present. If the listen() queue is empty of connection requests and O_NONBLOCK is set on the file descriptor for the socket, accept() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].
Source: http://pubs.opengroup.org/onlinepubs/9699919799/functions/accept.html
Also, select
or poll
can be used to check for incoming connections by polling for the listening socket in the reading set.
Norswap
Updated on March 29, 2020Comments
-
Norswap about 4 years
I'm looking for a way to interrupt an
accept()
call on a blocking socket. Using signals is not an option, as this is meant to be in a library and I don't want to clutter the user signals. Usingselect()
is another option, buf for various reason it's not very appealing in my case.What would work well, if possible, is to set the socket to non-blocking mode (using
fcntl()
andO_NONBLOCK
) from another thread, while the socket is blocked on anaccept()
call. The expected behaviour is that theaccept()
call will return withEAGAIN
orEWOULDBLOCK
inerrno
.Would it indeed work like that? Is it safe? Portable?
If you know about the applicability of this method to Windows (where you need to use
WSAIoctl()
andFONBIO
), I'm also interested. -
alk over 11 yearsAre you sure an already blocking
accept()
would return as specified, if the file descriptor having been passed getsO_NONBLOCK
set asynchronously? Your quote seems ambiguous to me for this case. -
R.. GitHub STOP HELPING ICE over 11 yearsOh, I misunderstood your question. No, I don't think changing the mode to non-blocking while it's already blocked is portable. Why don't you just make it nonblocking to begin with, and use
poll
orselect
prior to theaccept
call, and only callaccept
if a connection is available? There are plenty of clean ways to makeselect
orpoll
return early, like the self-pipe trick. -
Norswap over 11 yearsOkay, so the definite answer is that it's not up possible. Both in theory and practice (I ended up trying it out, both on Linux and Windows).
-
doron about 4 yearsOn windows you should use OVERLAPPED io. For portability I would suggest using Boost Asio.
-
Norswap about 4 yearsThanks for your answer, but the question was asked 8 years ago. In truth, I do not even remember what I was trying to achieve back then!
-
JamieB over 2 yearsOn Windows (WinSock) you can actually just close the socket from another thread. This will unblock any threads blocking on that socket.
-
R.. GitHub STOP HELPING ICE over 2 years@JamieB: That is not a safe operation ever, and carries with it the possibility of something else being opened on the same fd number, which the accept could continue on after interruption by a signal.