c++ how to use select to see if a socket has closed

前端 未结 3 748
失恋的感觉
失恋的感觉 2020-11-30 06:19

Can someone provide me an example of how to use select() to see if a client has closed the connection on a socket?

FYI. I\'m using linux.

Thanks!

3条回答
  •  感动是毒
    2020-11-30 06:44

    You don't need to do a select() followed by ioctl(). You can instead do a non-blocking peek on the socket to see if it returns 0.

    bool isclosed (int sock) {
        char x;
    interrupted:
        ssize_t r = ::recv(sock, &x, 1, MSG_DONTWAIT|MSG_PEEK);
        if (r < 0) {
            switch (errno) {
            case EINTR:     goto interrupted;
            case EAGAIN:    break; /* empty rx queue */
            case ETIMEDOUT: break; /* recv timeout */
            case ENOTCONN:  break; /* not connected yet */
            default:        throw(errno);
            }
        }
        return r == 0;
    }
    

提交回复
热议问题