Readiness Multiplexing: select & poll

Unthrottled O_NONBLOCK loops burn 100% CPU while blocking read() stalls on the first quiet stream. You will multiplex nonblocking channels at 0% idle CPU with select() and poll(), contrast destructive 1024-bit fd_set bitmasks against reusable struct pollfd arrays, prevent FD_SETSIZE stack overflows, and quantify stateless O(N) kernel scan costs.

20 minfree previewLinux 6.12C11glibc 2.39→ module 1 lab
What you'll learn
  • Implement zero-idle-CPU readiness waits with select() and poll(), retrying cleanly on EINTR interruptions.
  • Validate select() nfds = max_fd + 1 bounds, FD_SETSIZE (1024) stack limits, and fd_set reinitialization.
  • Differentiate requested events (POLLIN, POLLOUT) from kernel revents (POLLERR, POLLHUP) in struct pollfd.

External Sleep, Multi-Channel Readiness & the 1024-FD Cliff

Imagine an legacy telemetry collector written around select() running smoothly in staging with 50 sockets. In production, an operator raises ulimit -n (RLIMIT_NOFILE) to 65,536; the instant client 1,025 connects (fd == 1024), FD_SET(1024, &rfds) silently overwrites saved stack registers past the 128 B fd_set buffer, crashing the daemon with stack corruption!

Why did engineers need readiness multiplexing in the first place, and why do select() and poll() differ so sharply in memory safety? From our previous work on O_NONBLOCK, nonblocking descriptors avoid single-channel deadlocks, yet require a mechanism to sleep at 0% CPU when all watched channels are quiet. Synchronous I/O multiplexing solves that gap: the caller passes an interest set into the Linux kernel and sleeps until at least one watched descriptor becomes ready, a timeout expires, or a signal arrives (EINTR).

note: Imagine a night-shift dispatch operator monitoring twenty pneumatic canister tubes. Instead of sprinting down the corridor testing every latch by hand, the operator rests at a central console until an arrival chime illuminates the exact numbered tubes holding arrived canisters.

Where it stops working: Unlike a permanently wired lamp board, stateless select() and poll() copy your entire descriptor list from user RAM into kernel space on every call and linearly attach and detach wait queues across all N entries in O(N) time.

definition - select() fd_set Bitmask & FD_SETSIZE: Introduced in 4.2BSD (1983) and standardized in POSIX.1, select() represents watched descriptors using three fixed-size fd_set bitmaps (1024 bits = 128 B in glibc) bounded by nfds = max_fd + 1 and destructively overwritten in place by the kernel on every return.

definition - poll() events vs revents Separation: Originated in AT&T System V Release 3 (SVR3, 1986) and adopted into POSIX.1-2001 to eliminate fixed bitmap ceilings and value-result clobbering, poll() accepts a variable-length struct pollfd array separating caller-requested events (POLLIN, POLLOUT) from kernel-written revents (POLLIN, POLLOUT, POLLERR, POLLHUP, POLLNVAL).

definition - O(N) Stateless Multiplexer Cost: Because neither select() nor poll() persists watched descriptors inside kernel memory across calls, both incur O(N) stateless multiplexer cost: every invocation copies the full descriptor specification from Ring 3 to Ring 0, walks all N file_operations->poll wait queues, and linearly scans all N slots upon wakeup.

definition - FD_SETSIZE = 1024 Stack-Corruption Trap: In glibc, fd_set is a compile-time unsigned long fds_bits[16] (128 B) array where FD_SET(fd, &set) sets bit fd without bounds checking; passing any fd >= FD_SETSIZE (1024) writes out-of-bounds stack or heap memory.

ast_m01_l02.svg — Rebuild fd_set and timeval before every select() call,…step 1/4
  1. Step 1. Step 1: Copy master_set into rfds and pass nfds = max_fd + 1 (< FD_SETSIZE = 1024) into select().
  2. Step 2. Step 2: select() mutates rfds (and Linux timeval) in place to hold only ready bits, requiring loop reinitialization.
  3. Step 3. Step 3: poll(pfds, nfds, timeout_ms) preserves pfds[i].events while writing POLLIN, POLLOUT, or POLLHUP into revents.
  4. Step 4. Step 4: Level-triggered readiness re-fires immediately on the next call until read() or close() clears the condition.

Figure 1.2a. Rebuild fd_set and timeval before every select() call, guard fd < FD_SETSIZE (1024), and prefer poll() for clean events/revents separation on modest fd counts.

fig_m01_l02_arch.svg — select() 128-byte fd_set bitmask ceiling versus poll()…

Figure 1.2. select() 128-byte fd_set bitmask ceiling versus poll() struct pollfd layout and stateless O(N) kernel poll_wait() traversal.

Kernel poll_wait() Mechanics, Bitmask Indexing & Scaling Math

Inside Linux 6.12 (fs/select.c, do_select() and do_sys_poll()), both syscalls execute the same underlying VFS mechanism: the kernel allocates a poll_wqueues table on the kernel stack/heap, loops i = 0 .. N-1, resolves struct file * from the process files_struct, and invokes vfs_poll(file, &table). Each stream's .poll handler calls poll_wait() to link a poll_table_entry onto its wait_queue_head_t and returns a readiness bitmask. If zero descriptors are ready, the task sleeps in TASK_INTERRUPTIBLE until any wait queue wakes it, then detaches all N wait-queue entries before returning to user space!

Both select() and poll() are strictly level-triggered (LT): as long as >= 1 unread byte sits in a receive buffer (or send space exists under POLLOUT), calling select() or poll() again returns immediately without sleeping. Notice the memory-layout and scaling arithmetic:

  • select() bit indexing (128 B fixed): On 64-bit glibc, FD_SET(fd, &s) executes s.fds_bits[fd / 64] |= (1UL << (fd % 64)). Passing fd = 1024 indexes fds_bits[16], writing 8 B past sizeof(fd_set) (128 B). Also remember nfds is max_fd + 1 (scanning bits 0 .. max_fd), and Linux select() mutates struct timeval *timeout in place to hold remaining time!
  • poll() array cost (8 B * N): Each struct pollfd packs int fd (4 B), short events (2 B), and short revents (2 B) = 8 B. At N = 10,000 connections (80 KiB array) waking 1,000 times/s with 1 active packet per wake, poll() copies 80 MiB/s across the user-kernel boundary and performs 10^7 vfs_poll() inspections/s just to process 1,000 packets!
poll(2) at a glance — GL-C03
poll(2)                     GL-C03 Quick Reference                     poll(2) NAME       poll, select - synchronous level-triggered I/O readiness multiplexing SYNOPSIS       #include <poll.h>       int poll(struct pollfd *fds, nfds_t nfds, int timeout);       #include <sys/select.h>       int select(int nfds, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *tv); DESCRIPTION       Sleeps until one or more watched file descriptors become ready for       nonblocking I/O, timeout elapses (milliseconds in poll, struct timeval       in select), or a signal interrupts the wait. Negative fds[i].fd entries       in poll() are ignored. RETURN VALUE       Returns positive count of ready descriptors, 0 on timeout expiration,       or -1 setting errno (never auto-restarted on EINTR even with       SA_RESTART). FLAGS       POLLIN Data or incoming connection is readable without blocking.        POLLOUT              Send buffer space is available for nonblocking writes.        POLLHUP              Peer closed all write endpoints; set in revents automatically.        POLLERR              Asynchronous stream error; set in revents automatically. ERRORS       EINTR  Signal delivered before readiness or timeout completion; loop              and retry.        EINVAL nfds exceeds RLIMIT_NOFILE (poll) or nfds is negative (select). Kernel Systems Academy                   Lesson 1.2                    poll(2) GL-C03 quick reference · full manual page: man 2 poll 

Probing select() Bitmask Mutation, Level-Triggering & poll() POLLHUP

Let us build select_poll_mux.c across three pipe2(..., O_NONBLOCK | O_CLOEXEC) channels. It guards max_fd < FD_SETSIZE, proves select(max_fd + 1, ...) wipes non-ready bits inside rfds while master_set preserves them (mutated=1), verifies level-triggered re-notification (lt_retrigger=1) before read() drains "ALPHA", and then runs poll() to read "BRAVO" while catching an automatic POLLHUP (pollhup=1) on closed pipe p2 with events completely intact (events_intact=1).

learner@ksa: ~/gl-c03/m01-l02
learner@ksa:~/gl-c03/m01-l02$ bat -H 21 -H 22 -H 23 -H 36 -H 37 -H 38 -H 39 -H 40 -H 58 -H 59 -H 60 -H 61 -H 62 -H 63 -H 64 -H 65 -H 66 -H 67 select_poll_mux.c File: select_poll_mux.c    #define _GNU_SOURCE    #include <errno.h>    #include <fcntl.h>    #include <poll.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/select.h>    #include <unistd.h>        int main(void) {        int p0[2], p1[2], p2[2];        if (pipe2(p0, O_NONBLOCK | O_CLOEXEC) == -1 ||            pipe2(p1, O_NONBLOCK | O_CLOEXEC) == -1 ||            pipe2(p2, O_NONBLOCK | O_CLOEXEC) == -1) {            return EXIT_FAILURE;        }            int max_fd = p0[0];        if (p1[0] > max_fd) max_fd = p1[0];      if (p2[0] > max_fd) max_fd = p2[0];        if (max_fd >= FD_SETSIZE) {            return EXIT_FAILURE;        }            fd_set master_set;        FD_ZERO(&master_set);        FD_SET(p0[0], &master_set);        FD_SET(p1[0], &master_set);        FD_SET(p2[0], &master_set);            if (write(p1[1], "ALPHA", 5U) != 5) {            return EXIT_FAILURE;        }            fd_set rfds = master_set;        struct timeval tv = {.tv_sec = 0, .tv_usec = 50000};        int s_rc1;      do {            s_rc1 = select(max_fd + 1, &rfds, NULL, NULL, &tv);        } while (s_rc1 == -1 && errno == EINTR);            int mutated = (s_rc1 == 1 && FD_ISSET(p1[0], &rfds) &&                       !FD_ISSET(p0[0], &rfds) && FD_ISSET(p0[0], &master_set));            rfds = master_set;        tv.tv_sec = 0;        tv.tv_usec = 50000;        int s_rc2 = select(max_fd + 1, &rfds, NULL, NULL, &tv);        char sbuf[8] = {0};        ssize_t s_bytes = read(p1[0], sbuf, sizeof(sbuf) - 1U);            if (write(p0[1], "BRAVO", 5U) != 5) {            return EXIT_FAILURE;        }        (void)close(p2[1]);            struct pollfd pfds[3] = {            {.fd = p0[0], .events = POLLIN, .revents = 0},            {.fd = p1[0], .events = POLLIN, .revents = 0},            {.fd = p2[0], .events = POLLIN, .revents = 0},        };        int p_rc;        do {            p_rc = poll(pfds, 3U, 50);      } while (p_rc == -1 && errno == EINTR);            char pbuf[8] = {0};        if (pfds[0].revents & POLLIN) {            (void)read(p0[0], pbuf, sizeof(pbuf) - 1U);        }        int poll_hup = ((pfds[2].revents & POLLHUP) != 0);        int events_intact = (pfds[0].events == POLLIN && pfds[1].events == POLLIN);            (void)close(p0[0]);        (void)close(p0[1]);        (void)close(p1[0]);        (void)close(p1[1]);        (void)close(p2[0]);            printf("select: fd_setsize=%d nfds=%d mutated=%d lt_retrigger=%d msg=%s(%zd)\n",               (int)FD_SETSIZE, max_fd + 1, mutated, s_rc2 == 1, sbuf, s_bytes);        printf("poll: ready=%d msg=%s pollhup=%d events_intact=%d\n",               p_rc, pbuf, poll_hup, events_intact);        return EXIT_SUCCESS;    }
  1. Always enforce max_fd < FD_SETSIZE (1024) before calling FD_SET() so high descriptor numbers can never smash the stack.
  2. select() requires max_fd + 1, mutates rfds and tv in place, and must retry cleanly on EINTR.
  3. poll() keeps .events read-only across iterations and reports POLLHUP in .revents automatically when p2[1] closes.

Live Linux 6.12 Execution & Syscall Trace

Compile and run select_poll_mux, then inspect strace to see glibc lower select() into pselect6(8, [3 5 7], ...) (reporting in [5] and updated left nanoseconds) and poll() returning 2 ([{fd=3, revents=POLLIN}, {fd=7, revents=POLLHUP}]).

learner@ksa: ~/gl-c03/m01-l02
learner@ksa:~/gl-c03/m01-l02gcc -std=c11 -Wall -Wextra -Werror -fdiagnostics-color=always select_poll_mux.c -o select_poll_muxlearner@ksa:~/gl-c03/m01-l02./select_poll_muxselect: fd_setsize=1024 nfds=8 mutated=1 lt_retrigger=1 msg=ALPHA(5)poll: ready=2 msg=BRAVO pollhup=1 events_intact=1learner@ksa:~/gl-c03/m01-l02echo $?0learner@ksa:~/gl-c03/m01-l02ls -A --color=alwaysselect_poll_muxselect_poll_mux.clearner@ksa:~/gl-c03/m01-l02
strace — learner@ksa: ~/gl-c03/m01-l02
learner@ksa:~/gl-c03/m01-l02strace -e \trace=openat,pipe2,pselect6,select,ppoll,poll,read,write,close ./select_poll_muxopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3close(3)                                = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832close(3)                                = 0pipe2([3, 4], O_NONBLOCK|O_CLOEXEC)     = 0pipe2([5, 6], O_NONBLOCK|O_CLOEXEC)     = 0pipe2([7, 8], O_NONBLOCK|O_CLOEXEC)     = 0write(6, "ALPHA", 5)                    = 5pselect6(8, [3 5 7], NULL, NULL, {tv_sec=0, tv_nsec=50000000}, NULL) = 1 (in [5], left {tv_sec=0, tv_nsec=49998640})pselect6(8, [3 5 7], NULL, NULL, {tv_sec=0, tv_nsec=50000000}, NULL) = 1 (in [5], left {tv_sec=0, tv_nsec=49999358})read(5, "ALPHA", 7)                     = 5write(4, "BRAVO", 5)                    = 5close(8)                                = 0poll([{fd=3, events=POLLIN}, {fd=5, events=POLLIN}, {fd=7, events=POLLIN}], 3, 50) = 2 ([{fd=3, revents=POLLIN}, {fd=7, revents=POLLHUP}])read(3, "BRAVO", 7)                     = 5close(3)                                = 0close(4)                                = 0close(5)                                = 0close(6)                                = 0close(7)                                = 0write(1, "select: fd_setsize=1024 nfds=8 m"..., 119) = 119+++ exited with 0 +++

Trace Dissection & Multiplexer Trade-Off Matrix

Notice two critical details in strace: even though we watched only 3 pipes (fds 3, 5, 7), pselect6 required nfds = 8 (max_fd + 1) and returned left {tv_sec=0, tv_nsec=49998640}, proving Linux mutates both the bitset and the timeout struct on return! Because fd 5 still held "ALPHA", the second pselect6 woke in < 1 µs (lt_retrigger=1). Next, closing write endpoint fd 8 caused poll() to report revents=POLLHUP on fd 7 (pollhup=1) without our requesting POLLHUP in .events.

Dimensionselect() (<sys/select.h>)poll() (<poll.h>)pselect() / ppoll()
Descriptor ceilingHard FD_SETSIZE = 1024 bit capUnbounded (RLIMIT_NOFILE)Matches 1024 / unbounded
User-space payload3 * 128 B = 384 B bitmaps8 B * nfds compact arrayAdds atomic sigset_t * mask
In-place mutationClobbers fd_set + Linux timevalPreserves .events; writes .reventstimespec is const (unmodified)
Sparse fd efficiencyScans 0 .. max_fd (O(max_fd))Scans nfds active slots (O(nfds))O(max_fd) vs O(nfds)
High-scale 10k costUnsafe (fd >= 1024 UB!)O(N) poll_wait per wakeupReplaced by stateful epoll

Production Pitfalls & Level-Triggered Spin Traps

warning: Symptom: Monitoring 3 descriptors (fd 0, fd 5, and fd 7) via select(3, &rfds, NULL, NULL, NULL) leaves fd 5 and fd 7 permanently deaf even when buffers fill. Root Cause: select()'s first parameter nfds is max_fd + 1 (8), not the descriptor count (3); passing 3 tells the kernel to inspect only bits 0, 1, and 2. Fix: Recompute max_fd across all active descriptors and pass max_fd + 1 (after verifying max_fd < FD_SETSIZE), or migrate to poll().

warning: Symptom: When a child worker closes its pipe write end, a parent poll() loop checking only if (pfd.revents & POLLIN) suddenly pins a CPU core at 100% forever. Root Cause: Closing the last pipe writer asserts POLLHUP in revents (sometimes with POLLIN if final bytes remain, and without POLLIN once empty); leaving pfd.fd >= 0 open makes level-triggered poll() return 1 (POLLHUP) instantaneously on every call! Fix: Drain any readable bytes first on POLLIN, and when read() == 0 or (revents & (POLLHUP | POLLERR | POLLNVAL)) has no unread bytes left, close(pfd.fd) and set pfd.fd = -1.

Guided & Independent Practice

Guided Practice: Draining Final Bytes Before POLLHUP Teardown

  1. Write 12 B ("FINAL_PACKET") into p2[1] and immediately call close(p2[1]) before calling poll(pfds, 3, 50) (Cue 1: inspect pfds[2].revents; Linux asserts POLLIN | POLLHUP simultaneously!).
  2. Complete the handler branch so it drains read() until 0 (EOF) before closing pfds[2].fd and setting pfds[2].fd = -1 (Cue 2: checking POLLHUP first and closing immediately would discard "FINAL_PACKET"!).

Independent Practice: CLOCK_MONOTONIC Scaling Benchmark (N = 16 vs N = 2048)

Write poll_scale_bench.c that opens N pipe2(..., O_NONBLOCK | O_CLOEXEC) pairs, writes 1 B to only the final pipe N - 1, runs 50 warmup iterations plus 200 timed poll() wakeups measured with clock_gettime(CLOCK_MONOTONIC, ...), and prints p50/p95/p99 nanoseconds per wakeup at N = 16 versus N = 2048 (Near transfer: verify linear ~100x latency growth; Far transfer: explain why a shared library helper calling poll(&pfd, 1, 100) on fd = 1500 is memory-safe whereas select() crashes the host process).

quiz · 1 of 4

A daemon watches two nonblocking sockets at fd = 4 and fd = 11 with select(). What value must it pass for nfds, and how must rfds be managed across iterations of its event loop?

quiz · 2 of 4

Silent-Compile Bug Autopsy: A plugin library inside a busy web server opens a temporary pipe (fd = 1080) and executes: fd_set s; FD_ZERO(&s); FD_SET(fd, &s); select(fd + 1, &s, NULL, NULL, NULL); What happens at runtime on glibc Linux?

quiz · 3 of 4

When a peer closes its write end of a pipe after sending 8 final bytes, what does poll() place in pfd.revents (assuming pfd.events = POLLIN), and in what order must your loop respond?

quiz · 4 of 4

(Review from GL-C02 & Lesson 1) While sleeping inside poll(pfds, nfds, 5000), your process handles a SIGCHLD signal installed with SA_RESTART. What does poll() return on Linux 6.12?

Because select() and poll() re-copy and re-scan every watched descriptor in O(N) time on every wakeup, scaling to 10,000+ concurrent connections requires keeping the interest set inside the kernel, which we build next with epoll, EPOLLET, eventfd(), and a structural comparison to io_uring.

Key takeaways

  • Synchronous I/O multiplexing (select() and poll()) sleeps in the Linux kernel at 0% CPU until at least one watched descriptor becomes ready, a timeout expires, or a signal interrupts the wait (EINTR).
  • select() requires nfds = max_fd + 1, enforces a hard FD_SETSIZE = 1024 descriptor-number ceiling, and destructively mutates fd_set bitmasks and Linux struct timeval structs on every call.
  • poll() takes a struct pollfd array separating caller-requested events (POLLIN, POLLOUT) from kernel-filled revents (including automatic POLLERR, POLLHUP, and POLLNVAL), avoiding the 1024 cap and in-place clobbering.
  • Both select() and poll() are level-triggered and cost O(N) kernel poll_wait() registration per wakeup, while passing fd >= FD_SETSIZE (1024) to FD_SET(fd, &rfds) overflows glibc's fixed 128-byte fd_set stack bitmap.
  • select() scans indices 0 through nfds - 1 (requiring nfds = max_fd + 1) and destructively mutates both fd_set bitmasks and Linux struct timeval structs on every call.
  • fd_set enforces a hard FD_SETSIZE = 1024 (128-byte) bitmap ceiling where fd >= 1024 writes out-of-bounds stack bits, whereas struct pollfd separates integer fd from events and revents.
  • Negative fd slots are ignored cleanly (revents = 0), while POLLERR, POLLHUP, and POLLNVAL are reported unconditionally in revents even when omitted from events.
  • Passing timeout = 0 checks descriptor readiness and returns 0 immediately when idle, whereas timeout = -1 sleeps at 0% CPU until readiness or EINTR.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure