Alternative I/O Models 1339
z POLLRDHUP is a Linux-specific flag available since kernel 2.6.17. In order to obtain
this definition from <poll.h>, the _GNU_SOURCE feature test macro must be defined.
z POLLNVAL is returned if the specified file descriptor was closed at the time of the
poll() call.
Summarizing the above points, the poll() flags of real interest are POLLIN, POLLOUT,
POLLPRI, POLLRDHUP, POLLHUP, and POLLERR. We consider the meanings of these flags in
greater detail in Section 63.2.3.
The timeout argument
The timeout argument determines the blocking behavior of poll() as follows:
z If timeout equals –1, block until one of the file descriptors listed in the fds array
is ready (as defined by the corresponding events field) or a signal is caught.
z If timeout equals 0, do not block—just perform a check to see which file descrip-
tors are ready.
z If timeout is greater than 0, block for up to timeout milliseconds, until one of the
file descriptors in fds is ready, or until a signal is caught.
As with select(), the accuracy of timeout is limited by the granularity of the software
clock (Section 10.6), and SUSv3 specifies that timeout is always rounded upward if it
is not an exact multiple of the clock granularity.
Return value from poll()
As its function result, poll() returns one of the following:
z A return value of –1 indicates that an error occurred. One possible error is
EINTR, indicating that the call was interrupted by a signal handler. (As noted in
Section 21.5, poll() is never automatically restarted if interrupted by a signal
handler.)
z A return of 0 means that the call timed out before any file descriptor became
ready.
z A positive return value indicates that one or more file descriptors are ready.
The returned value is the number of pollfd structures in the fds array that have a
nonzero revents field.
Note the slightly different meaning of a positive return value from select() and
poll(). The select() system call counts a file descriptor multiple times if it occurs
in more than one returned file descriptor set. The poll() system call returns a
count of ready file descriptors, and a file descriptor is counted only once, even
if multiple bits are set in the corresponding revents field.
Example program
Listing 63-2 provides a simple demonstration of the use of poll(). This program
creates a number of pipes (each pipe uses a consecutive pair of file descriptors),
writes bytes to the write ends of randomly selected pipes, and then performs a
poll() to see which pipes have data available for reading.