How do I check client connection is still alive

徘徊边缘 提交于 2019-12-06 00:27:58

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!