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..
You use EPOLLRDHUP
to detect peer shutdown, not EPOLLHUP
(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 of EPOLLIN
write EPOLLIN|EPOLLRDHUP
.
After epoll_wait
, do an if(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 from EPOLLIN
but before you call read
, if you are in ET mode, you'll not get another notification).
socket
call fails, what else is there to do but output a message and exit. On the other hand, read
can (and will often) fail, which is a perfectly normal thing if the error is EAGAIN. Just read the "return value" and "error codes" sections of the man pages. –
Dished read
would return "zero bytes read", then EPOLLRDHUP
must already be set. In practice, I've seen strange things happen in edge-triggered mode (level-triggered is 100% reliable in every way from what I can tell) which are not entirely conform from what the docs say either. Therefore, to be on the 100% safe side, in edge-triggered mode, I would check whether read
returns "zero read", just to be sure. It doesn't really cost anything, and it puts you in a 100% failsafe position. –
Dished © 2022 - 2024 — McMap. All rights reserved.