Skip to content
Visual explainer 5h to learn 5 steps

select, poll & epoll

Serve many clients from one thread by multiplexing descriptors with epoll.

By Invicly Tech, , in Linux System Programming. About 14 minutes to read.

Topic 35 of 42

In short

A server handling many clients cannot block on one socket while others wait. select, poll and epoll let one thread wait for readiness on many descriptors at once and then service only the ready ones. epoll is the scalable Linux choice because its cost depends on active descriptors, not on how many are watched.

Explained simply

A waiter in a restaurant does not stand at one table until those guests finish eating. They walk around and serve whichever table is ready. I/O multiplexing lets one thread work the same way with many network connections.

Instead of calling read on one socket and getting stuck there, you ask the kernel: "Here is my list of sockets. Wake me up when any of them has something for me." The kernel answers with the ones that are ready, and you serve only those.

Linux offers three ways to ask. select is the oldest and has a hard limit of 1024 descriptors. poll removes that limit but still checks every socket on every call. epoll remembers your list inside the kernel and only reports the ready ones, so it stays fast with tens of thousands of connections.

"Ready" has a precise meaning: the next read or write will not block. It does not mean a whole message has arrived. Your code still has to collect bytes until a full message is there.

Press Play on a diagram to walk through it one step at a time.

Compareselect vs poll vs epoll
select
  • Fixed fd_set, fds below 1024 only
  • Sets rebuilt before every call
  • Scans every descriptor
  • Portable everywhere
poll
  • Array of pollfd, no fd limit
  • Whole list passed on every call
  • Still scans every descriptor
  • Simple and portable
epoll
  • Kernel keeps the interest list
  • Returns only ready descriptors
  • Scales to tens of thousands of connections
  • Linux only; level or edge triggered
SequenceRegistering once, then waiting many times
Server
epoll instance
Client socket
  1. 1epoll_create1
    Server to epoll instance: epoll_create1
  2. 2epoll_ctl ADD fd, EPOLLIN
    Server to epoll instance: epoll_ctl ADD fd, EPOLLIN
  3. 3epoll_wait (sleeps)
    Server to epoll instance: epoll_wait (sleeps)
  4. 4data arrives: fd joins ready list
    Client socket to epoll instance: data arrives: fd joins ready list
  5. 5returns 1 event for fd
    epoll instance to Server: returns 1 event for fd
  6. 6read the data
    Server to Client socket: read the data
  7. 7epoll_wait again: no re-registration
    Server to epoll instance: epoll_wait again: no re-registration

In depth

select: the original interface

select takes three fd_set bitmaps (for read, write and exceptional conditions), the highest descriptor plus one, and a timeout. You fill the sets with FD_ZERO and FD_SET, call select, then test each descriptor with FD_ISSET. The kernel overwrites the sets with the ready ones, so you must rebuild them before every call. On Linux the timeout struct is also changed to the time left, so reset it too.

The big limit is FD_SETSIZE, 1024. An fd_set is a fixed bitmap, and calling FD_SET with descriptor 1024 or higher writes past its end: memory corruption, not a clean error. A busy server reaches descriptor 1024 easily, because every connection, file and pipe takes a number. Building with -D_FORTIFY_SOURCE=2 and optimisation makes glibc abort on such calls instead of corrupting memory. select is still fine for small tools that watch a few descriptors, like a terminal and one socket.

  • Rebuild the fd_sets and the timeout before every call
  • nfds = highest descriptor + 1
  • Never FD_SET a descriptor of 1024 or more

poll: an array instead of bitmaps

poll takes an array of struct pollfd. Each entry has fd, the events you want (POLLIN for readable, POLLOUT for writable) and revents, which the kernel fills in. The timeout is in milliseconds: -1 waits forever, 0 returns at once. There is no 1024 limit, and poll never changes fd or events, so you can pass the same array again on the next call. Setting an entry's fd to -1 makes poll skip it, which is a handy way to remove a client without reshuffling the array.

revents can also contain flags you never asked for: POLLERR (an error is pending), POLLHUP (the peer hung up) and POLLNVAL (the descriptor is not open, usually a bug in your bookkeeping). Always check them.

The cost remains linear. On every call the kernel copies the whole array in, checks every descriptor, and copies it out. With 10,000 mostly idle connections, each call does 10,000 checks to find perhaps 3 ready sockets.

  • struct pollfd { int fd; short events; short revents; }
  • POLLHUP and POLLERR arrive even if not requested
  • fd = -1 disables an entry

epoll: interest list and ready list

epoll splits the work in two. epoll_create1 creates an epoll instance, itself a descriptor. epoll_ctl with EPOLL_CTL_ADD, EPOLL_CTL_MOD or EPOLL_CTL_DEL changes the interest list, which the kernel keeps in a red-black tree. You register each socket once, not on every call.

When you add a socket, epoll hooks a callback onto that socket's wait queue. When data arrives, the network stack wakes the queue, the callback puts the socket on the ready list, and epoll_wait returns only the entries on that list. So the cost of each epoll_wait depends on how many sockets are ready, not on how many you watch.

The epoll_event you register carries a data field. Instead of the fd, store a pointer to your connection struct in data.ptr, so each event leads straight to its state. One trap: epoll tracks the underlying open file, not the number. Closing a descriptor only removes it from epoll if no duplicate (from dup or fork) still refers to it, so call EPOLL_CTL_DEL first if in doubt.

FlowHow a packet wakes epoll_wait
  1. 1
    Packet arrives

    NIC and TCP stack queue the data

  2. 2
    Socket wait queue

    The stack wakes everyone waiting

  3. 3
    epoll callback

    Puts the socket on the ready list

  4. 4
    epoll_wait returns

    Copies only ready events to you

  5. 5
    You read

    Using data.ptr to find the connection

Level-triggered vs edge-triggered

By default epoll is level-triggered, like poll: as long as a socket has unread data, every epoll_wait reports it. If you read only part of the data, you are told again next time. This is forgiving and works with blocking or non-blocking sockets.

With EPOLLET (edge-triggered), you are told only when the state changes, for example when new data arrives in an empty buffer. If you read half and return, no new event comes until more data arrives, which may be never. So with EPOLLET you must use non-blocking sockets and read (or accept, or write) in a loop until EAGAIN. In return, a busy socket does not generate repeated events, which saves some wakeups.

Two more flags help with threads. EPOLLONESHOT disables a descriptor after one event until you re-arm it with EPOLL_CTL_MOD, so two threads never handle the same connection at once. EPOLLEXCLUSIVE (Linux 4.5) wakes only one of several epoll instances waiting on the same listening socket, avoiding a thundering herd.

CompareLevel- vs edge-triggered epoll
Level-triggered (default)
  • Reports while data remains
  • Partial reads are safe
  • Blocking sockets work
  • More repeated events
Edge-triggered (EPOLLET)
  • Reports only on change
  • Must drain until EAGAIN
  • Non-blocking sockets required
  • Fewer wakeups when busy

Benchmarking the three fairly

The difference between select, poll and epoll only shows with many connections of which few are active. With 10 busy sockets, all three perform about the same, and select or poll can even win because they need no setup calls.

A fair test opens a large number of idle connections (1,000, then 10,000), keeps a small fixed number busy with request-response traffic, and measures requests per second and CPU time of the server for each method. First raise the descriptor limit with ulimit -n, and remember select cannot go past 1024 at all. Measure with perf stat or /usr/bin/time -v for CPU time, and strace -c to count and time system calls.

Expect poll's cost per call to grow in step with the number of idle connections, while epoll stays flat. That flat line is why nginx, Redis, Node.js and every high-connection Linux server uses epoll.

  • ulimit -n 65536 before opening many connections
  • Vary idle connections, keep active ones fixed
  • strace -c -p PID shows time spent per system call

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Watch descriptors with select~1h
  2. 2
    Scale further with poll~1h
  3. 3
    Register interest with epoll_ctl~1h
  4. 4
    Compare level- and edge-triggered modes~1h
  5. 5
    Benchmark the three approaches~1h

Key points

  • Readiness means a call will not block, not that a whole message has arrived.
  • Level-triggered epoll keeps reporting a ready fd until you drain it; edge-triggered reports only changes.
  • In edge-triggered mode, use non-blocking descriptors and read until EAGAIN.
  • Watch the listening socket too; readable means a connection is waiting to be accepted.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
int ep = epoll_create1(EPOLL_CLOEXEC);
struct epoll_event ev = { .events = EPOLLIN, .data.fd = listen_fd }, evs[64];
epoll_ctl(ep, EPOLL_CTL_ADD, listen_fd, &ev);
for (;;) {
  int n = epoll_wait(ep, evs, 64, -1);
  for (int i = 0; i < n; i++) {
    int fd = evs[i].data.fd;
    if (fd == listen_fd) {
      int c = accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK);
      struct epoll_event cev = { .events = EPOLLIN, .data.fd = c };
      epoll_ctl(ep, EPOLL_CTL_ADD, c, &cev);
    } else if (handle_client(fd) <= 0) { close(fd); }
  }
}

Core of an epoll server; handle_client reads, replies and returns 0 on disconnect.

A poll-based echo server for many clients

One thread serves many clients with poll. Step 1: slot 0 of the array is the listening socket; the other slots hold clients, with fd -1 meaning free. Step 2: poll waits for any of them. Step 3: if the listener is readable, accept and put the new client in a free slot (or close it if the table is full). Step 4: for each readable client, read once and echo; on 0 or an error, close it and free the slot. Partial sends are ignored here to keep it short; the event-loop topic handles them.

c
struct pollfd p[256] = { [0] = { .fd = lfd, .events = POLLIN } };
for (int i = 1; i < 256; i++) p[i].fd = -1;
for (;;) {
  if (poll(p, 256, -1) < 0) { if (errno == EINTR) continue; perror("poll"); break; }
  if (p[0].revents & POLLIN) {
    int c = accept(lfd, NULL, NULL), i = 1;
    while (c >= 0 && i < 256 && p[i].fd != -1) i++;
    if (c >= 0) { if (i < 256) p[i] = (struct pollfd){ .fd = c, .events = POLLIN }; else close(c); }
  }
  for (int i = 1; i < 256; i++) if (p[i].fd >= 0 && p[i].revents & (POLLIN | POLLHUP | POLLERR)) {
    char buf[4096]; ssize_t n = recv(p[i].fd, buf, sizeof buf, 0);
    if (n > 0) send(p[i].fd, buf, n, MSG_NOSIGNAL); else { close(p[i].fd); p[i].fd = -1; }
  }
}

Edge-triggered epoll with per-connection state

Each client gets a struct conn, and epoll hands it back through data.ptr. Step 1: register the non-blocking socket with EPOLLIN | EPOLLET | EPOLLRDHUP and the struct pointer. Step 2: on an event, take the struct from data.ptr. Step 3: because the mode is edge-triggered, read in a loop until EAGAIN; stopping early would lose the notification. Step 4: on 0 (peer closed) or a real error, remove it from epoll, close it and free the struct. EPOLLRDHUP alone is not a reason to close at once, because unread data may still be waiting; the read loop reaches 0 after it.

c
struct conn { int fd; char in[4096]; size_t len; };
/* when accepting (c was created with SOCK_NONBLOCK): */
struct conn *k = calloc(1, sizeof *k); k->fd = c;
struct epoll_event ev = { .events = EPOLLIN | EPOLLET | EPOLLRDHUP, .data.ptr = k };
if (epoll_ctl(ep, EPOLL_CTL_ADD, c, &ev) < 0) { perror("epoll_ctl"); close(c); free(k); }
/* when an event arrives: */
struct conn *k = evs[i].data.ptr;
for (;;) {
  ssize_t n = read(k->fd, k->in + k->len, sizeof k->in - k->len);
  if (n > 0) { k->len += n; if (handle_lines(k) == 0) continue; }   /* -1: bad input, close */
  if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) break;   /* drained */
  if (n < 0 && errno == EINTR) continue;
  epoll_ctl(ep, EPOLL_CTL_DEL, k->fd, NULL); close(k->fd); free(k); break;  /* EOF, error or bad input */
}

Quick reference

  • select: fds below 1024 only; rebuild sets and timeout every call
  • poll(fds, n, timeout_ms): -1 waits forever, 0 just checks
  • Check POLLERR, POLLHUP and POLLNVAL in revents even if not requested
  • epoll_create1(EPOLL_CLOEXEC); epoll_ctl ADD once; epoll_wait in the loop
  • Store a struct pointer in ev.data.ptr instead of the bare fd
  • EPOLLET needs non-blocking fds and loops until EAGAIN
  • EPOLLONESHOT + EPOLL_CTL_MOD to re-arm: one thread per event
  • Raise the fd limit with ulimit -n or LimitNOFILE= in systemd

Common mistakes

  • Using select with descriptors numbered 1024 or higher.
  • Not draining an edge-triggered descriptor and never being notified again.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A select-based server crashes randomly once it has about 1000 clients. What is the likely cause?

Question 2

2Why is epoll_wait cheap even with 50,000 idle connections?

Question 3

3With EPOLLET, a handler reads 100 of the 300 waiting bytes and returns. What happens next?

Question 4

4What does POLLNVAL in revents usually mean?

Question 5

5Two threads share one epoll instance. How do you stop both handling the same connection at once?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a program that uses poll to wait on standard input and a 3-second timeout: print what you type, or "tick" when 3 seconds pass with no input.

  2. Exercise 2medium

    Turn the explainer's epoll loop into a working echo server: error checks, non-blocking client sockets, level-triggered mode, EPOLL_CTL_DEL and close on disconnect.

  3. Exercise 3hard

    Benchmark poll against epoll: open 5,000 idle connections to each server, keep 10 clients doing echo round trips, and compare the server's CPU time over 30 seconds.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I still use select in new code?
Only for small programs with a few low-numbered descriptors. Use poll for portable code and epoll for Linux servers with many connections.
Does epoll work with regular files?
No. epoll_ctl returns EPERM for regular files, because they are always considered ready. Disk reads are handled with threads or io_uring instead.
What is the difference between epoll and io_uring?
epoll tells you when a socket is ready so you can then call read or write. io_uring lets you submit the reads and writes themselves and get completions later, which also works for files and saves system calls.
Is epoll available on macOS?
No, epoll is Linux-only. macOS and the BSDs use kqueue; libraries like libuv and libevent hide the difference.

Go deeper

ShareXLinkedInWhatsApp