Search code examples
csocketsposix-select

Check Socket File Descriptor is Available?


If I got a file descriptor (socket fd), how to check this fd is avaiable for read/write? In my situation, the client has connected to server and we know the fd. However, the server will disconnect the socket, are there any clues to check it ?


Solution

  • You want fcntl() to check for read/write settings on the fd:

    #include <unistd.h>
    #include <fcntl.h>
    
    int    r;
    
    r = fcntl(fd, F_GETFL);
    if (r == -1)
            /* Error */
    if (r & O_RDONLY)
        /* Read Only */
    else if (r & O_WRONLY)
        /* Write Only */
    else if (r & O_RDWR)
        /* Read/Write */
    

    But this is a separate issue from when the socket is no longer connected. If you are already using select() or poll() then you're almost there. poll() will return status nicely if you specify POLLERR in events and check for it in revents.

    If you're doing normal blocking I/O then just handle the read/write errors as they come in and recover gracefully.