An application system can multiplex I/O requests among multiple
sockets by using select, as shown for the Internet domain:
select(nfds, &readfds, &writefds, &execptfds, &timeout);
The select call takes three I/O descriptor sets as arguments:
Bit masks are created by or-ing bits of the form ``1 << fd''. That is, a descriptor fd is selected if a 1 is present in the fd'th bit of the mask. The parameter nfds specifies the range of file descriptors (that is, one plus the value of the largest descriptor) specified in a mask.
The macros FD_SET(fd, &mask) and FD_CLR(fd, &mask) have been provided for adding and removing file descriptor fd in the set mask. The set should be zeroed before use, and the macro FD_ZERO(&mask) has been provided to clear the set mask. The parameter nfds in the select call specifies the range of file descriptors (one plus the value of the largest descriptor) to be examined in a set.
A timeout value may be specified if the selection is not to last more than a predetermined period of time. If timeout is set to 0, the selection takes the form of a poll, returning immediately. If the last parameter is a null pointer, the selection will block indefinitely. (A return takes place only when a descriptor is selectable, or when a signal is received by the caller, interrupting the system call.) The select call normally returns the number of file descriptors selected. If the select call returns due to the timeout expiring, then a value of -1 is returned along with the error number EINTR.
Assuming a successful return, the three sets will indicate which file descriptors are ready to be read from, written to, or have exceptional conditions pending. The status of a file descriptor in a select mask may be tested with the FD_ISSET(fd, &mask) macro, which returns a non-zero value if fd is a member of the set mask, and 0 if it is not.
To determine whether there are connections waiting on a socket to be used with an accept call, select can be used, followed by a FD_ISSET(fd, &mask) macro to check for read readiness on the appropriate socket. IfFD_ISSET returns a non-zero value, indicating permission to read, then a connection is pending on the socket.