C Programming/POSIX Reference/unistd.h/select

From Wikibooks, open books for an open world
Jump to navigation Jump to search

select is a system call and application programming interface (API) in Unix-like and POSIX-compliant operating systems for examining the status of file descriptors of open input/output channels. The select system call is similar to the poll facility introduced in UNIX System V and later operating systems.

In the C programming language source code, the select system call is declared in the header file sys/select.h or unistd.h, and has the following syntax:

int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* errorfds, struct timeval* timeout);
argument description
nfds the maximum file descriptor across all the sets, plus 1
readfds fd_set type holding the file descriptors to be checked for being ready to read, and on output indicates which file descriptors are ready to read. Can be NULL.
writefds fd_set type holding the file descriptors to be checked for being ready to write, and on output indicates which file descriptors are ready to write. Can be NULL.
errorfds fd_set type holding the file descriptors to be checked for error conditions pending, and on output indicates which file descriptors have error conditions pending. Can be NULL.
timeout structure of type struct timeval that specifies a maximum interval to wait for the selection to complete. If the timeout argument points to an object of type struct timeval whose members are 0, select() does not block. If the timeout argument is NULL, select() blocks until an event causes one of the masks to be returned with a valid (non-zero) value.

fd_set type arguments may be manipulated with four utility macros: FD_SET(), FD_CLR(), FD_ZERO(), and FD_ISSET().

Select returns the total number of bits set in readfds, writefds and errorfds, or zero if the timeout expired, and -1 on error.

The sets of file descriptor used in select are finite in size, depending on the operating system. The newer system call poll provides a more flexible solution.

See also[edit | edit source]

External links[edit | edit source]