select

Function

Enable I/O multiplexing

Function Prototype

totalFds = select(nfds, readfds, writefds, errorfds, timeout)
  • nfds - the range of file descriptors to check
  • readfds - a bit map, set bit to check whether file descriptor is ready for reading
  • writefds - set bit to check whether file descriptors is ready for writing
  • errorfds - bit map to check for errors
  • timeout - how long to wait before stop blocking the process
  • totalFds - number of ready descriptors, 0 for timeout, negative for error

How does it works?

  • When we call select, the process is put to sleep and the kernel will help us monitor the file descriptor we specify
  • Once a file descriptor is ready or timeout, the kernel will revise readfds, writefds, or errorfds making only the file descriptor which is ready to be 1
  • The kernel will then awake the process, then we can scan through readfds, writefds, and errorfds to find which file descriptor is ready
  • Eventually, the process can operate on the file

Disadvantages

  1. To tell the process which file descriptor is available, select need to modify readfds, writefds, …
  2. If we only need to monitor fd 1000, we still need to set nfds to 1001