Is there a OS portable way of interrupting a blocking accept
? I have a multi-threaded deamon/service that needs to gracefully close all listening network hosts when the deamon/service gets a shutdown signal. I see that some say you should use non-blocking sockets or select with a time-out - but won't these degrade performance as my application should be as fast as possible? The deamon runs in the main thread while each of the listening network hosts run in their own thread. The problem now is that accept
wait indefinitely if there is no network traffic on the listening network host's socket. If I should use signals, then is there an example somewhere of using signals to interrupt accept
?
Asked
Active
Viewed 3,212 times
3
-
possible duplicate of [How can I interrupt a ServerSocket accept() method?](http://stackoverflow.com/questions/2983835/how-can-i-interrupt-a-serversocket-accept-method) – Jonathan Potter Jun 29 '13 at 21:18
-
2@JonathanPotter That answer is for Java, this question is tagged with C & C++. – Jun 29 '13 at 21:20
-
2@JonathanPotter that question is about Java, does it apply to C/C++ as well? – Kninnug Jun 29 '13 at 21:20
-
@Kninnug Yes, all those techniques will work in C or C++. – user207421 Jun 30 '13 at 00:36
-
The other way is to open an actual temporary client connection on the local stack. The Accept() will then return as designed and can check some 'shutdownRequested' bool to see if the server is shutting down. – Martin James Jul 01 '13 at 09:14
-
Answered here: https://stackoverflow.com/a/62356967/70405 . Don't mind the boost involvement, solution is at socket API level. – Alex Jun 13 '20 at 09:29
-
Does this answer your question? [Boost::asio - how to interrupt a blocked tcp server thread?](https://stackoverflow.com/questions/11191028/boostasio-how-to-interrupt-a-blocked-tcp-server-thread) – Alex Jun 13 '20 at 09:30
1 Answers
5
The solution here is to not call accept
when there's nothing to do. Just use non-blocking select
or poll
to wait until there's something to accept, then accept
at that point. Unless you create a really tiny timeout there won't be any performance implications of waking up from the non-blocking call and going back to wait on that socket again.

Mark B
- 95,107
- 10
- 109
- 188
-
4Blocking select or poll will work too, and will be more CPU efficient and have quicker response time than waiting for a timeout. You just need a way to tell select()/poll() to wake up. Typically you would use a pipe or socketpair() to do that... have select() wait-for-read-ready on one end of the pipe/socketpair (as well as the accept socket, of course), and then to wake up select() at any time, write a byte to the other end of the pipe/socketpair. – Jeremy Friesner Jun 29 '13 at 22:37