如果接收不到数据,如何防止接收套接字永远阻塞?

How to prevent receive socket from blocking forever in case it receives no data?

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

您可以使用 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
    }
}