ptg10805159
502 Advanced I/O Chapter 14
I/O multiplexing was provided with theselectfunction in 4.2BSD. This function has
always worked with any descriptor,although its main use has been for terminal I/O and
network I/O. SVR3 added thepollfunction when the STREAMS mechanism was added.
Initially,pollworked only with STREAMS devices. In SVR4, support was added to allow
pollto work on any descriptor.
14.4.1 selectandpselect Functions
The select function lets us do I/O multiplexing under all POSIX-compatible
platforms. The arguments we pass toselecttell the kernel
•Which descriptors we’reinterested in.
•Which conditions we’reinterested in for each descriptor.(Do we want to read
from a given descriptor? Do we want to write to a given descriptor? Arewe
interested in an exception condition for a given descriptor?)
•How long we want to wait. (Wecan wait forever,wait a fixed amount of time,
or not wait at all.)
On the return fromselect,the kernel tells us
•The total count of the number of descriptors that areready
•Which descriptors areready for each of the three conditions (read, write, or
exception condition)
With this return information, we can call the appropriate I/O function (usuallyreador
write)and know that the function won’t block.
#include <sys/select.h>
int select(intmaxfdp1,fd_set *restrict readfds,
fd_set *restrict writefds,fd_set *restrict exceptfds,
struct timeval *restricttvptr);
Returns: count of ready descriptors, 0 on timeout,−1 on error
Let’s look at the last argument first. It specifies how long we want to wait in terms
of seconds and microseconds (recall Section 4.20). Thereare three conditions.
tvptr== NULL
Wait forever.This infinite wait can be interrupted if we catch a signal. Return
is made when one of the specified descriptors is ready or when a signal is
caught. Ifasignal is caught,selectreturns−1witherrnoset toEINTR.
tvptr−>tv_sec== 0 &&tvptr−>tv_usec== 0
Don’t wait at all. All the specified descriptors aretested, and return is made
immediately.This is a way to poll the system to find out the status of multiple
descriptors without blocking in theselectfunction.