Search code examples
csocketsposix-select

why do I need to update nfds in select call when I remove fds from master set?


Given a select call like this:

select(fdMax+1, &readFds, NULL, NULL, &timeoutVal)

where readFds are updated whenever

  • new fd is added
  • existing fd is removed

Whenever new fd is added, I update the fdMax. However, whenever existing fd is removed, I'm wondering if I really need to update the fdMax also ?

What difference does it make if I have a higher fdMax in there with not enough fds to read on ?


Solution

  • You could just set fdMax to the maximum file descriptor value supported by your system (which may be represented by FD_SETSIZE), and not worry about it, but it may cause inefficiencies. select will use the fdMax value as a hint of when it can stop its linear scan of the file descriptor table. If you lie to select, it will likely cause it to loop for much longer than is actually needed to find the file descriptors of interest.

    In Linux, the function max_select_fd uses the fdMax to start a backward scan for the relevant file descriptors.LXR

    In FreeBSD, the function kern_select will adjust fdMax to the highest open file descriptor for the process if fdMax is larger.FXR For a pure server, this looks to be a good heuristic choice, but may still be too large for a system that is careful to keep socket file descriptors at lower values than other file descriptors.