Alternative I/O Models 1331
We can use select() and poll() to monitor file descriptors for regular files, termi-
nals, pseudoterminals, pipes, FIFOs, sockets, and some types of character devices.
Both system calls allow a process either to block indefinitely waiting for file descrip-
tors to become ready or to specify a timeout on the call.
63.2.1 The select() System Call
The select() system call blocks until one or more of a set of file descriptors becomes
ready.
The nfds, readfds, writefds, and exceptfds arguments specify the file descriptors that
select() is to monitor. The timeout argument can be used to set an upper limit on the
time for which select() will block. We describe each of these arguments in detail below.
In the prototype for select() shown above, we include <sys/time.h> because that
was the header specified in SUSv2, and some UNIX implementations require
this header. (The <sys/time.h> header is present on Linux, and including it
does no harm.)
File descriptor sets
The readfds, writefds, and exceptfds arguments are pointers to file descriptor sets, repre-
sented using the data type fd_set. These arguments are used as follows:
z readfds is the set of file descriptors to be tested to see if input is possible;
z writefds is the set of file descriptors to be tested to see if output is possible; and
z exceptfds is the set of file descriptors to be tested to see if an exceptional condi-
tion has occurred.
The term exceptional condition is often misunderstood to mean that some sort of
error condition has arisen on the file descriptor. This is not the case. An exceptional
condition occurs in just two circumstances on Linux (other UNIX implementations
are similar):
z A state change occurs on a pseudoterminal slave connected to a master that is
in packet mode (Section 64.5).
z Out-of-band data is received on a stream socket (Section 61.13.1).
Typically, the fd_set data type is implemented as a bit mask. However, we don’t
need to know the details, since all manipulation of file descriptor sets is done via
four macros: FD_ZERO(), FD_SET(), FD_CLR(), and FD_ISSET().
#include <sys/time.h> /* For portability */
#include <sys/select.h>
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
struct timeval *timeout);
Returns number of ready file descriptors, 0 on timeout, or –1 on error