I/O
Overview
By default, all file descriptors on Unix start out in blocking mode. Performing an I/O operation on the underlying stream will cause the process to wait until the operation can be performed. In contrast, nonblocking mode indicates that waiting should not happen. I/O operations always return immediately, though possibly with an error state indicating the action could not be performed.
Multiplexing
I/O multiplexing refers to any method that allows a single thread to handle multiple I/O streams concurrently. Notice this definition's relation to network multiplexing.
Select
The select function allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become ready for some class of I/O operation.
int select(int numfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
In general, this function should not be used. It can only monitor file descriptors numbers less than 1024 and has a number of bugs (e.g. reporting a socket as ready to read when it isn't).
Poll
The poll function is the preferred alternative to select. It waits for one of a set of file descriptors to become ready to perform I/O.
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
Like select, it may falsely claim a file descriptor as ready when it isn't.
Event Poll
The epoll family of functions is the preferred alternative to poll on Linux systems. It operates in one of two modes:
- Level-Triggered (LT). In this case, calls to
epoll_waitfirst check if any descriptor in the interest list already matches the interest condition. - Edge-Triggered (ET). In this case, calls to
epoll_waitimmediately put the process to sleep.
int epoll_create(int size);
int epoll_ctl(int epfd, int op, int fd,
struct epoll_event *_Nullable event);
int epoll_wait(int epfd, struct epoll_event events[.maxevents],
int maxevents, int timeout);