Search code examples
socketsnetwork-programmingudpsystem-callsblocking

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


In case of a blocking UDP socket blocking on receive does not receive any data, and is not going to receive any data because the sender process has crashed for some reason. The socket option SO_RCVTIMEO could be set to make sure the receive system call is going to return, but is there a "known approach" to solve that problem(since the value of the timeout is not precise and depends on the system if it is slow or not)


Solution

  • You can use select function to know a something is ready to be read on a socket.

    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
        }
    }