中断accept() [英] Interrupting accept()

查看:88
本文介绍了中断accept()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有OS便携式方法来中断阻塞的 accept ?我有一个多线程守护进程/服务,当守护进程/服务收到关闭信号时,它需要正常关闭所有侦听网络主机.我看到有人说您应该使用非阻塞套接字或使用超时进行选择-但是这些不会降低性能,因为我的应用程序应该尽可能快吗?守护进程在主线程中运行,而每个侦听网络主机在其自己的线程中运行.现在的问题是,如果侦听网络主机的套接字上没有网络流量,则 accept 会无限期地等待.如果我应该使用信号,那么是否有一个使用信号来中断 accept 的示例?

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?

推荐答案

这里的解决方案是在无事可做时不调用 accept .只需使用无阻塞的 select poll 来等待,直到有东西可以接受,然后再接受 accept .除非您创建一个非常小的超时,否则从非阻塞调用中唤醒并再次等待该套接字不会对性能产生任何影响.

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.

这篇关于中断accept()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆