~/Using the select System Call in C

Jan 18, 2021


The select system call in C monitors multiple file descriptors to see if any are ready for I/O. It is often used for multiplexing sockets or files within a single thread.

Basic usage steps:

  1. Initialize an fd_set variable.
  2. Use FD_ZERO, FD_SET, FD_ISSET, FD_CLR macros.
  3. Set a timeout struct timeval.
  4. Call select with the highest fd plus one, and pointers to read, write, and except sets.

Minimal example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <sys/select.h>
#include <unistd.h>

int main() {
    fd_set readfds;
    struct timeval timeout;
    int fd = 0; // standard input
    int ret;

    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);

    timeout.tv_sec = 5; // timeout in seconds
    timeout.tv_usec = 0;

    ret = select(fd + 1, &readfds, NULL, NULL, &timeout);

    if(ret == -1) {
        perror("select");
    } else if(ret == 0) {
        printf("timeout\n");
    } else if(FD_ISSET(fd, &readfds)) {
        printf("data available on stdin\n");
    }
}

Each set parameter can be NULL if not needed. FD_SET and macros help manage fd_set variables. select returns the number of ready descriptors, 0 for timeout, -1 for error.

Use cases include simple non-blocking socket multiplexing. For large numbers of fds, consider poll or epoll.

Tags: [C] [sockets] [select]