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.
What you'll learn
- Implement zero-idle-CPU readiness waits with
select()andpoll(), retrying cleanly onEINTRinterruptions. - Validate
select()nfds = max_fd + 1bounds,FD_SETSIZE(1024) stack limits, andfd_setreinitialization. - Differentiate requested
events(POLLIN,POLLOUT) from kernelrevents(POLLERR,POLLHUP) instruct 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.
- Step 1. Step 1: Copy master_set into rfds and pass nfds = max_fd + 1 (< FD_SETSIZE = 1024) into select().
- Step 2. Step 2: select() mutates rfds (and Linux timeval) in place to hold only ready bits, requiring loop reinitialization.
- Step 3. Step 3: poll(pfds, nfds, timeout_ms) preserves pfds[i].events while writing POLLIN, POLLOUT, or POLLHUP into revents.
- 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.
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 Bfixed): On 64-bitglibc,FD_SET(fd, &s)executess.fds_bits[fd / 64] |= (1UL << (fd % 64)). Passingfd = 1024indexesfds_bits[16], writing8 Bpastsizeof(fd_set)(128 B). Also remembernfdsismax_fd + 1(scanning bits0 .. max_fd), and Linuxselect()mutatesstruct timeval *timeoutin place to hold remaining time!poll()array cost (8 B * N): Eachstruct pollfdpacksint fd(4 B),short events(2 B), andshort revents(2 B) =8 B. AtN = 10,000connections (80 KiBarray) waking1,000times/s with1active packet per wake,poll()copies80 MiB/sacross the user-kernel boundary and performs10^7vfs_poll()inspections/s just to process1,000packets!
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$ 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; }- Always enforce
max_fd < FD_SETSIZE(1024) before callingFD_SET()so high descriptor numbers can never smash the stack. select()requiresmax_fd + 1, mutatesrfdsandtvin place, and must retry cleanly onEINTR.poll()keeps.eventsread-only across iterations and reportsPOLLHUPin.reventsautomatically whenp2[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-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-l02learner@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.
| Dimension | select() (<sys/select.h>) | poll() (<poll.h>) | pselect() / ppoll() |
|---|---|---|---|
| Descriptor ceiling | Hard FD_SETSIZE = 1024 bit cap | Unbounded (RLIMIT_NOFILE) | Matches 1024 / unbounded |
| User-space payload | 3 * 128 B = 384 B bitmaps | 8 B * nfds compact array | Adds atomic sigset_t * mask |
| In-place mutation | Clobbers fd_set + Linux timeval | Preserves .events; writes .revents | timespec is const (unmodified) |
Sparse fd efficiency | Scans 0 .. max_fd (O(max_fd)) | Scans nfds active slots (O(nfds)) | O(max_fd) vs O(nfds) |
High-scale 10k cost | Unsafe (fd >= 1024 UB!) | O(N) poll_wait per wakeup | Replaced 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
- Write
12 B("FINAL_PACKET") intop2[1]and immediately callclose(p2[1])before callingpoll(pfds, 3, 50)(Cue 1: inspectpfds[2].revents; Linux assertsPOLLIN | POLLHUPsimultaneously!). - Complete the handler branch so it drains
read()until0(EOF) before closingpfds[2].fdand settingpfds[2].fd = -1(Cue 2: checkingPOLLHUPfirst 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).
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()andpoll()) sleeps in theLinux kernelat0%CPU until at least one watched descriptor becomes ready, a timeout expires, or a signal interrupts the wait (EINTR). select()requiresnfds = max_fd + 1, enforces a hardFD_SETSIZE = 1024descriptor-number ceiling, and destructively mutatesfd_setbitmasks and Linuxstruct timevalstructs on every call.poll()takes astruct pollfdarray separating caller-requestedevents(POLLIN,POLLOUT) from kernel-filledrevents(including automaticPOLLERR,POLLHUP, andPOLLNVAL), avoiding the1024cap and in-place clobbering.- Both
select()andpoll()are level-triggered and costO(N)kernelpoll_wait()registration per wakeup, while passingfd >= FD_SETSIZE(1024) toFD_SET(fd, &rfds)overflowsglibc's fixed128-bytefd_setstack bitmap. select()scans indices0throughnfds - 1(requiringnfds = max_fd + 1) and destructively mutates bothfd_setbitmasks and Linuxstruct timevalstructs on every call.fd_setenforces a hardFD_SETSIZE = 1024(128-byte) bitmap ceiling wherefd >= 1024writes out-of-bounds stack bits, whereasstruct pollfdseparates integerfdfromeventsandrevents.- Negative
fdslots are ignored cleanly (revents = 0), whilePOLLERR,POLLHUP, andPOLLNVALare reported unconditionally inreventseven when omitted fromevents. - Passing
timeout = 0checks descriptor readiness and returns0immediately when idle, whereastimeout = -1sleeps at0%CPU until readiness orEINTR.