Interrupting accept()

2019-02-25 17:00发布

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?

1条回答
在下西门庆
2楼-- · 2019-02-25 17:00

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.

查看更多
登录 后发表回答