I/O multiplexing: A list of descriptors is constructed first, and then a function is called until one of these descriptors is ready for I/O and the function returns. When returned, it tells the process which descriptors are ready to be I/O.
The three functions poll, Pselect, and select Enable us to perform I/O multiplex transfer.
One, select function
On all POSIX-compliant platforms, the Select function allows us to perform I/O multiplexing. The parameters that are passed to select tell the kernel:
The descriptor we care about.
For each descriptor we are concerned about the state. (Do you want to read a given descriptor?) Do you want to write a given descriptor? Are you concerned about a descriptor exception state? )
How long will you wait (you can always wait, wait for a fixed amount of time, or not wait at all).
When returned from Select, the kernel tells us:
The number of prepared descriptors.
Which descriptors are ready for each of the three states of read, write, or exception.
#include <sys/select.h>
int Select (int maxfdp1,fd_set *readfds,fd_set *writefds,fd_set *exceptfds,struct Timeval *tvptr);//return value: Number of prepared descriptors, return 0 if the timeout occurs, or 1 if an error occurs
Describes the last parameter, which specifies the time to wait:
struct timeval{
long tv_sec;//seconds
long Tv_usec;//and microseconds
}
There are three kinds of situations:
Tvptr = NULL
Wait forever. If you catch a signal, you interrupt this indefinitely wait. Returns when one of the specified descriptors is ready or catches a signal. If a signal is captured, the select returns -1,errno set to Eintr
tvptr->tv_sec = 0 && tvptr->tv_usec = 0
Do not wait at all. Tests all the specified descriptors and returns immediately.
Tvptr->tv_sec! = 0 | | Tvptr->tv_usec! = 0
Waits for the specified number of seconds and subtleties. Returns immediately when one of the specified descriptors is ready or when the specified time value has expired. If no descriptor is ready when the timeout occurs, the return value is 0. As in the first case, this wait can be captured by the signal interruption.
The middle three parameters Readfds, Writefds, and Exceptfds are pointers to descriptor sets. These three descriptor sets describe the various descriptors that we care about, readable, writable, or in exceptional conditions. Each descriptor set is stored in a Fd_set data type. This data type holds one digit for each possible descriptor.