csocketsposix-select

c: select hangs on empty fd_set


The following code snippet calls the select() function.

n = select(max_fd, NULL, &write_set, NULL, NULL)

It checks write availability on some sockets. Because it is usually available, so timeout is not set. In certain loop iteration, it is possible that write_set could be empty.

Below is the trace. There is no further output so I assume the program hangs.

select(7, NULL, [], NULL, NULL

My question is: Is it the right behavior? If the set is empty, should the select just return immediately? There is no reason for the select()to wait, right?


Solution

  • Yes, this is correct behavior. POSIX says

    select() blocks, up to the specified timeout interval, until the specified condition is true for at least one of the specified file descriptors.

    If no FDs are specified, then "true for at least one of the specified file descriptors" will never be true, so it blocks until the timeout.

    If the timeout argument is a null pointer, select() blocks until an event causes one of the masks to be returned with a valid (non-zero) value.
    ...
    If the readfds, writefds, and errorfds arguments are all null pointers and the timeout argument is a null pointer, select() blocks until interrupted by a signal.

    An empty FD set is effectively the same as passing a null pointer for that set.