Lesson 14 of 18 Concurrency and I/O

select(): Classic I/O Multiplexing

Use select() with fd_set, FD_SET, FD_ISSET and timeouts to watch sockets and the keyboard together. Includes a server console example and select's limits.

40-50 min intermediate 0/18 lessons done
Course contents Lesson 14 of 18 · 0 done
On this page (9 sections)
  1. What you will learn
  2. The API
  3. Example: server with an operator console
  4. Readable” can mean end-of-stream
  5. A subtle trap: select() and buffered stdin
  6. select() vs poll()
  7. Key takeaways
  8. Exercises
  9. Quiz

What you will learn

  • The select() API and its four FD_* macros.
  • Why you must copy the descriptor set before every call.
  • How to watch sockets and standard input together.
  • The limits of select() (FD_SETSIZE, signals, timeout updates) and when to prefer poll().

The API

select() predates poll() and is found everywhere, including Windows. Instead of an array of structs it uses bit sets of descriptors:

#include <sys/select.h>

int select(int nfds,                /* highest fd in any set, plus 1 */
           fd_set *readfds,         /* watch for readability (or NULL) */
           fd_set *writefds,        /* watch for writability (or NULL) */
           fd_set *exceptfds,       /* exceptional conditions, rarely used */
           struct timeval *timeout);/* NULL = wait forever */

FD_ZERO(&set);        /* clear all bits */
FD_SET(fd, &set);     /* add fd */
FD_CLR(fd, &set);     /* remove fd */
FD_ISSET(fd, &set);   /* is fd in the set? */

On return, select() has overwritten each set so it contains only the ready descriptors. It returns how many are ready, 0 on timeout, -1 on error.

That overwrite is the classic bug: if you pass your master set directly, you lose track of everybody who wasn’t ready. Always keep a master set and copy it:

fd_set ready = everyone;    /* struct copy */
select(max_fd + 1, &ready, NULL, NULL, NULL);

Example: server with an operator console

This server prints whatever clients send, and anything the operator types into the server’s terminal is announced to every client. One select() watches the keyboard (STDIN_FILENO), the listener and all clients.

/* select_console.c - TCP server watched with select(), plus an operator console.
 * Lines from clients are printed on the server; lines typed on the server's
 * keyboard are sent to every client as announcements. Usage: ./select_console 7171 */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

static int open_listener(const char *port)
{
    struct addrinfo hints, *res, *ai;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if (getaddrinfo(NULL, port, &hints, &res) != 0)
        return -1;
    int fd = -1;
    for (ai = res; ai != NULL; ai = ai->ai_next) {
        fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (fd == -1)
            continue;
        int on = 1;
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);
        if (bind(fd, ai->ai_addr, ai->ai_addrlen) == 0 && listen(fd, 16) == 0)
            break;
        close(fd);
        fd = -1;
    }
    freeaddrinfo(res);
    return fd;
}

int main(int argc, char *argv[])
{
    const char *port = argc > 1 ? argv[1] : "7171";
    int listener = open_listener(port);
    if (listener == -1) {
        fprintf(stderr, "cannot listen on port %s\n", port);
        return 1;
    }

    fd_set everyone;                   /* the master set we maintain */
    FD_ZERO(&everyone);
    FD_SET(STDIN_FILENO, &everyone);
    FD_SET(listener, &everyone);
    int max_fd = listener;

    printf("listening on %s; type a line to announce it\n", port);

    for (;;) {
        fd_set ready = everyone;       /* select() overwrites its argument */
        struct timeval tick = { .tv_sec = 30, .tv_usec = 0 };

        int n = select(max_fd + 1, &ready, NULL, NULL, &tick);
        if (n == -1) {
            if (errno == EINTR)
                continue;              /* a signal interrupted us: just retry */
            perror("select");
            return 1;
        }
        if (n == 0) {
            printf("(30 s with no activity)\n");
            continue;
        }

        for (int fd = 0; fd <= max_fd; fd++) {
            if (!FD_ISSET(fd, &ready))
                continue;

            if (fd == listener) {
                int client = accept(listener, NULL, NULL);
                if (client == -1) {
                    perror("accept");
                } else if (client >= FD_SETSIZE) {
                    close(client);     /* select() cannot watch it */
                } else {
                    FD_SET(client, &everyone);
                    if (client > max_fd)
                        max_fd = client;
                    printf("client on fd %d\n", client);
                }
            } else if (fd == STDIN_FILENO) {
                char line[256];
                if (fgets(line, sizeof line, stdin) == NULL)
                    return 0;          /* operator pressed Ctrl-D */
                for (int c = 0; c <= max_fd; c++)
                    if (c != listener && c != STDIN_FILENO && FD_ISSET(c, &everyone))
                        send(c, line, strlen(line), MSG_NOSIGNAL);
            } else {
                char buf[512];
                ssize_t got = recv(fd, buf, sizeof buf, 0);
                if (got <= 0) {
                    printf("fd %d disconnected\n", fd);
                    close(fd);
                    FD_CLR(fd, &everyone);
                } else {
                    printf("fd %d: %.*s", fd, (int)got, buf);
                    fflush(stdout);
                }
            }
        }
    }
}

Highlights:

  • max_fd + 1. select() checks descriptors 0 to nfds - 1, so track the highest one you’ve added.
  • A 30-second timeout shows the idle path. On Linux, select() modifies the timeval to show the time left, so we re-create it each loop. Don’t rely on either behaviour; always reset it.
  • FD_SETSIZE guard. An fd_set holds descriptors below FD_SETSIZE (usually 1024). Calling FD_SET with a larger fd corrupts memory, so we refuse such clients.
  • EINTR. A signal (resizing the terminal can send one) makes select() fail with EINTR; just loop again.
gcc -Wall -o select_console select_console.c
./select_console 7171
# another terminal:
nc localhost 7171

Type in nc and the server prints it; type in the server’s terminal and every nc sees the announcement.

”Readable” can mean end-of-stream

When a client disconnects, its socket becomes readable and recv() returns 0. That’s why the “readable” branch always checks for 0 and cleans up. The same holds for poll().

A subtle trap: select() and buffered stdin

We read stdin with fgets(). If the user pastes several lines at once, fgets() pulls them all into stdio’s buffer but returns only one; select() then sees an empty kernel buffer and won’t report stdin again until more is typed. For robust console handling, read() from the descriptor directly and split lines yourself.

select() vs poll()

select()poll()
Descriptor limitFD_SETSIZE (often 1024)None beyond process limits
InterfaceBit sets, rebuilt every callArray of structs; revents separate from events
PortabilityEverywhere, including WinsockPOSIX; Windows has WSAPoll
Timeout precisionMicroseconds (timeval)Milliseconds

Prefer poll() in new Unix code; use select() when you need maximum portability or are maintaining code that already uses it.

Key takeaways

  • select() watches read, write and exception sets and overwrites them with the ready descriptors.
  • Keep a master set, copy it before each call, and pass max_fd + 1.
  • Reset the timeout each loop and handle EINTR.
  • Respect FD_SETSIZE; for large or new programs prefer poll() or epoll.

Exercises

  1. Add a /kick N operator command that disconnects the client on fd N.
  2. Rewrite select_console.c to use poll() and compare the two versions line by line.
  3. Use the write set: make one client socket non-blocking, queue a large announcement, and send the rest only when select() says it’s writable.

Quiz

  1. Why do we copy the master fd_set before each select() call?
  2. What value must the first argument of select() have?
  3. What happens if you FD_SET() descriptor 2000 on a system where FD_SETSIZE is 1024?
Show answers
  1. select() overwrites the sets with only the ready descriptors, so the original membership would be lost.
  2. The highest descriptor number in any of the sets, plus one.
  3. Undefined behaviour: it writes past the end of the fd_set, typically corrupting nearby memory. Use poll() for high descriptor numbers.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).