【问题标题】:How to prevent receive socket from blocking forever in case it receives no data?如果接收套接字没有接收到数据,如何防止它永远阻塞?
【发布时间】:2017-04-15 18:23:11
【问题描述】:

在阻塞 UDP 套接字的情况下,blocking on receive 不接收任何数据,并且不会接收任何数据,因为发送方进程由于某种原因崩溃了。 可以设置套接字选项SO_RCVTIMEO 以确保接收系统调用将返回,但是是否有“已知方法”来解决该问题(因为超时的值不精确并且取决于系统是否慢与否)

【问题讨论】:

    标签: sockets networking udp system-calls blocking


    【解决方案1】:

    您可以使用select 函数知道某个内容已准备好在套接字上读取。

    while (1)
    {
        int retval;
        fd_set rfds;
        // one second timeout
        struct timeval tv = {1,0};
    
        FD_ZERO(&rfds);
        FD_SET(fd, &rfds);
    
        retval = select(1, &rfds, NULL, NULL, &tv);
    
        if (retval == -1)
        {
            perror("select()");
            exit(1);
        }        
        else if (retval)
        {
            printf("Data is available now.\n"); 
            // if recvfrom() is called here, it won't block
        }
        else
        {
            // no data to read... perform other tasks
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多