How do I check client connection is still alive
Asked Answered
I

2

6

I am working on a network programming using epoll. I have a connection list and put every client in the list. I can detect user disconnection by reading 0 if the user disconnected normally. However, if the user somehow got disconnected unexpectedly then there is no way it knows about this until it tries send data to the user.

I don't think epoll provides a nice way to handle this..so I think I should handle this on my own. I will be very appreciated if you guys can provide me anything like examples or references related to this problem.

Intrauterine answered 22/6, 2011 at 2:39 Comment(0)
G
8

epoll_wait will return a EPOLLHUP or EPOLLERR for the socket if the other side disconnects. EPOLLHUP and EPOLLERR are set automatically but you can also set the newer EPOLLRDHUP which explicitly reports peer shutdown.

Also if you use send with the flag MSG_NOSIGNAL it will set EPIPE on closed connections.

int resp = send ( sock, buf, buflen, MSG_NOSIGNAL );

if ( resp == -1 && errno == EPIPE ) { /* other side gone away */ }

Much nicer than getting a signal.

Grouch answered 22/6, 2011 at 17:44 Comment(3)
It's actually EPOLLRDHUP, see kernel.org/doc/man-pages/online/pages/man2/epoll_ctl.2.htmlDoorbell
Yup, EPOLLRDHUP is the better option.Grouch
@MartinRedmond I read similar solutions regarding the use of EPOLLRDHUP but this does not work in my system. It is undefined but after I define it it still does not work. my kernel version is 3.2.0-38-generic.Moulding
H
1

How about TCP Keepalives: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html. See "Checking for dead peers". A later section on the same site has example code: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/programming.html.

Hendecagon answered 22/6, 2011 at 3:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.