Skip to content

select()

Purpose

Waits for readiness on a small set of file descriptors using fd_set bit masks.

#include <sys/select.h>

Prototype

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);

Parameters

  • nfds: highest fd value plus one.
  • readfds: fds monitored for readability.
  • writefds: fds monitored for writability.
  • exceptfds: exceptional conditions.
  • timeout: maximum wait time, or NULL to block indefinitely.

Return Value

  • Success: returns number of ready fds.
  • Timeout: returns 0.
  • Failure: returns -1 and sets errno.

Minimal Example

fd_set rfds;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);

int ret = select(fd + 1, &rfds, NULL, NULL, NULL);

Common Pitfalls

  • fd_set is modified by select(), so rebuild it before each call.
  • FD_SETSIZE limits how many fd numbers can be represented.
  • Prefer poll() or epoll() for scalable event loops.