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

前端 未结 3 745
失恋的感觉
失恋的感觉 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:32

    The below snippet first checks if the socket is marked readable (which it is when closed) and then if there's actually anything to be read.

    #include 
    #include 
    #include 
    #include 
    
    bool isclosed(int sock) {
      fd_set rfd;
      FD_ZERO(&rfd);
      FD_SET(sock, &rfd);
      timeval tv = { 0 };
      select(sock+1, &rfd, 0, 0, &tv);
      if (!FD_ISSET(sock, &rfd))
        return false;
      int n = 0;
      ioctl(sock, FIONREAD, &n);
      return n == 0;
    }
    

提交回复
热议问题