How to let a thread which blocks on recv() exit gracefully?

后端 未结 7 1819
暗喜
暗喜 2020-12-11 17:27

There is a thread likes this:

{  
    ......    
    while (1)
    {
        recv(socket, buffer, sizeof(buffer), 0);
        ......
    }
    close(socket         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-11 18:04

    Also, set your socket to be nonblocking:

    int listen_sd = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
    if (listen_sd < 0) {
        perror("socket() failed");
    }
    
    int on = 1;
    
    //set socket to be non-blocking
    int rc = ioctl(listen_sd, FIONBIO,(char *)&on);
    if (rc < 0) {
        perror("ioctl() failed");
        close(listen_sd);
    }
    

    Then, you can call recv() on the socket, and it won't block. If there's nothing to read then the ERRNO global variable is set to the constant EWOULDBLOCK

    int rc = recv(listen_sd, buffer, sizeof(buffer), 0);
    if (rc < 0) {
        if (errno != EWOULDBLOCK) {
            perror("recv() failed");
        }
    }
    

提交回复
热议问题