如何使用 EPOLLHUP
你们能给我提供一个使用 EPOLLHUP 进行死对等处理的良好示例代码吗?我知道这是检测用户断开连接的信号,但不确定如何在代码中使用它。提前致谢。
Could you guys provide me a good sample code using EPOLLHUP for dead peer handling? I know that it is a signal to detect a user disconnection but not sure how I can use this in code..Thanks in advance..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用
EPOLLRDHUP
来检测对等关闭,而不是EPOLLHUP
(它表示套接字意外关闭,即通常是内部错误)。使用它非常简单,只需将该标志与您提供给 epoll_ctl 的任何其他标志“或”即可。因此,例如,不要写
EPOLLIN
,而是写EPOLLIN|EPOLLRDHUP
。在
epoll_wait
之后,执行if(my_event.events & EPOLLRDHUP)
,然后执行如果对方关闭连接时您想要执行的任何操作(您可能想要关闭插座)。请注意,从套接字读取时获得“零字节读取”结果也意味着另一端已关闭连接,因此您也应该始终检查这一点,以避免令人讨厌的意外(< code>FIN 可能在您从
EPOLLIN
中唤醒之后但在您调用read
之前到达,如果你处于 ET 模式,你将无法获得另一个 通知)。You use
EPOLLRDHUP
to detect peer shutdown, notEPOLLHUP
(which signals an unexpected close of the socket, i.e. usually an internal error).Using it is really simple, just "or" the flag with any other flags that you are giving to
epoll_ctl
. So, for example instead ofEPOLLIN
writeEPOLLIN|EPOLLRDHUP
.After
epoll_wait
, do anif(my_event.events & EPOLLRDHUP)
followed by whatever you want to do if the other side closed the connection (you'll probably want to close the socket).Note that getting a "zero bytes read" result when reading from a socket also means that the other end has shut down the connection, so you should always check for that too, to avoid nasty surprises (the
FIN
might arrive after you have woken up fromEPOLLIN
but before you callread
, if you are in ET mode, you'll not get another notification).