How does socket select() work?

Tural Gurbanov picture Tural Gurbanov · Feb 4, 2013 · Viewed 12k times · Source

As described in network programming books, select() monitors a set of file descriptors for reading. For example, here is part of code:

select(numfds, &read_fds, NULL, NULL, NULL);

Here numfds is maximum number of socket in read_fds + 1. Does it mean, that every "monitor" cycle select() watchs through all file descriptors of the process from 0 to numfds? I mean, if I have only two file descriptors to monitor(0 and 26), does select watch all descriptors from 0 to 26?

Answer

nneonneo picture nneonneo · Feb 4, 2013

select chooses which fds to watch based on the fd sets you pass in (readfds, writefds, exceptfds). The sets are typically implemented as bit vectors, so select will scan over the vector to see what fds are selected. As an optimization, you pass in the number of fds to scan up to so that select doesn't have to look at all fds up to FD_SETSIZE (which might not even be the same across compilation units).

select is a fairly expensive call because of the scanning and the necessity of resetting the sets after every call to select. On many platforms, select is just implemented on top of the poll system call, which offers a more efficient interface for waiting on file descriptors.