Search code examples
csocketsposixposix-select

POSIX C non-blocking read socket


I'm trying to create a thread to read from a socket descriptor. I need to do this with a non-blocking loop to check the current time and close the socket after the session end, but FD_ISSET returns 0 even if on a socket that can read data.

fd_set fds;
FD_ZERO(&fds);
FD_SET(session_ref->fd, &fds);

while(1)
{
    while(1)
    {
        FD_CLR(session_ref->fd, &fds);
        FD_SET(session_ref->fd, &fds);
        n = select( session_ref->fd, &fds, NULL, NULL, &timeout ); // n = 0 
        if( FD_ISSET( session_ref->fd, &fds ) )
            break;
        else 
        {
            // some operations
        }
        sleep(1);
    }
    n = read( session_ref->fd, buffer, 2048 );
    printf("Read: %i\n", n);
}

Where did I make a mistake?


Solution

  • You should pass the highest file descriptor value + 1, that's why n == 0

    n = select( session_ref->fd, &fds, NULL, NULL, &timeout ); // n = 0 
    

    has to be

    n = select( 1 + session_ref->fd, &fds, NULL, NULL, &timeout ); // n = 0 
    

    and then check how many files in the set are ready

    if ((n > 1) && (FD_ISSET( session_ref->fd, &fds ) != 0))
    

    in your case, since there is only one file in the set, it would actually be

    if ((n == 1) && (FD_ISSET( session_ref->fd, &fds ) != 0))