Course Onboarding & Nonblocking I/O
Welcome to Course 3 (GL-C03) in the Linux Systems Programming in C11 track. Building on GL-C01 open-file descriptions and GL-C02 process, signal, and thread primitives, you will contrast TASK_INTERRUPTIBLE wait-queue sleep against O_NONBLOCK status flags, handle EAGAIN and EWOULDBLOCK safely, and quantify why unthrottled polling loops waste 100% of a CPU core.
What you'll learn
- Apply
GL-C01struct fileflags andGL-C02signal rules to multiplex concurrent nonblocking C11 I/O channels. - Contrast blocking
TASK_INTERRUPTIBLEwait-queue sleep against immediate-1(EAGAIN) returns underO_NONBLOCK. - Configure
O_NONBLOCKatomically viaopen()/pipe2(O_NONBLOCK | O_CLOEXEC)andfcntl(F_GETFL/F_SETFL).
Scaling Past Thread-Per-Stream Blocking Stalls
Suppose an industrial telemetry collector monitors 10,000 sensor pipes and TCP streams simultaneously. If a single-threaded daemon calls default blocking read(ch_a, buf, 64) on a quiet sensor channel, the Linux kernel suspends that thread until ch_a transmits, starving 9,999 sibling channels that already hold urgent alarms in kernel RAM.
Why does spawning 10,000 POSIX threads or fork() worker processes fail as an alternative? At 8 MiB default virtual stack reservation (ulimit -s) and at least 8 KiB to 16 KiB of resident dirty stack and kernel task_struct state per thread, 10,000 threads consume 80 MiB to 160 MiB of unswappable overhead and thrash L1/L2 CPU caches across scheduler context switches.
Welcome to Course 3 (GL-C03: Advanced I/O, IPC, Sockets, CMake & MQTT in C) in our four-course C11 series (GL-C01 -> GL-C02 -> GL-C03 -> GL-C04). Extending GL-C01 VFS descriptors (struct file, f_pos, f_flags) and GL-C02 signal and concurrency primitives, high-throughput C11 daemons decouple concurrency from thread count by combining nonblocking descriptor status flags (O_NONBLOCK) with kernel readiness multiplexing.
note: Picture a laboratory technician tending two pneumatic specimen chutes. Standing motionless in front of Chute A until a capsule drops starves Chute B, whereas checking a spring-loaded empty latch on Chute A lets the technician service Chute B immediately; however, sprinting back and forth nonstop without an arrival bell wastes all available energy.
Where it stops working: Unlike glancing at a mechanical latch in zero time, every nonblocking read() traps across the Ring 3 to Ring 0 syscall boundary (~150 to 300 ns on modern CPUs) to inspect kernel struct file->f_flags and buffer state before returning -1 with errno == EAGAIN.
definition - Nonblocking File Flag (O_NONBLOCK): Standardized in IEEE Std 1003.1 (POSIX.1) to unify earlier System V O_NDELAY (which ambiguously returned 0 on empty streams) and BSD FNDELAY, O_NONBLOCK (0x800 on x86_64 Linux) is an open-file description status flag stored in struct file->f_flags that forces read(), write(), accept(), or connect() on unready slow descriptors to return -1 immediately instead of sleeping in a kernel wait queue.
definition - EAGAIN Readiness Retry Contract: Introduced in POSIX.1 to separate transient buffer exhaustion from 0-byte end-of-file (EOF), the EAGAIN / EWOULDBLOCK contract guarantees that an unready O_NONBLOCK transfer returns -1 with thread-local errno set to EAGAIN (11 on Linux, identical to EWOULDBLOCK), signaling the caller to retry only after kernel readiness notification.
definition - : The busy-wait spin anti-pattern occurs when user-space code wraps O_NONBLOCK read() or write() calls inside an unthrottled for (;;) loop without a blocking readiness multiplexer, burning 100% of a CPU core in repeated Ring-3-to-Ring-0 EAGAIN syscall traps while all channels sit idle.
- Step 1. Step 1: Default blocking read() enqueues current on wait_queue_head_t and sleeps in TASK_INTERRUPTIBLE while a pipe is empty.
- Step 2. Step 2: O_NONBLOCK lives in shared struct file->f_flags, set atomically via open()/pipe2() or merged via fcntl(F_GETFL/F_SETFL).
- Step 3. Step 3: Nonblocking read() sees an empty pipe_inode_info ring and returns -1 (errno == EAGAIN) so live sibling fds proceed.
- Step 4. Step 4: Tight EAGAIN polling loops saturate 100% CPU in syscall traps, motivating kernel readiness sleep in the next lesson.
Figure 1.1a. Enable O_NONBLOCK via open(), pipe2(), or fcntl(F_GETFL/F_SETFL), distinguish -1 (EAGAIN) from 0 (EOF), and never spin in an unthrottled polling loop.
Figure 1.1. Kernel open-file description f_flags, pipe_inode_info wait-queue sleep versus O_NONBLOCK -EAGAIN return, and busy-poll syscall trap cost.
Kernel Wait Queues, VFS Object Classes & Syscall Trap Math
One layer down inside Linux 6.12 (fs/pipe.c, pipe_read()), every slow stream owns a struct pipe_inode_info (or struct sock) containing a circular page ring and a wait_queue_head_t rd_wait sleep list. When pipe_read() finds head == tail (zero buffered bytes) and writers still exist, it inspects filp->f_flags & O_NONBLOCK: if clear, the kernel sets task state to TASK_INTERRUPTIBLE, adds current (struct task_struct *) to rd_wait, and calls schedule(), consuming 0% CPU; if set, pipe_read() returns -EAGAIN immediately so glibc stores EAGAIN in errno and returns -1.
Crucially, O_NONBLOCK governs slow descriptors whose arrival time depends on external producers: pipes, FIFOs, sockets, eventfd/timerfd descriptors, and character devices (/dev/tty*). Regular disk files (S_IFREG) backed by the VFS page cache are always deemed immediately ready by POSIX: passing O_NONBLOCK to open("/tmp/data.bin", ...) neither suppresses NVMe block-layer waits nor returns EAGAIN.
Let us quantify why busy-polling O_NONBLOCK descriptors fails in production. On a modern x86_64 or ARMv7 Cortex-A7 Linux 6.12 host with KPTI/Spectre mitigations, one empty read() syscall trap costs roughly t_trap ~= 200 ns (0.2 µs). Calling read() across 2 idle pipes in a tight for (;;) loop executes 1 / (400 ns) = 2.5 * 10^6 iterations (5.0 * 10^6 syscalls) every second, pinning 100% of a CPU core and burning watts to transfer 0 B/s!
Configure O_NONBLOCK cleanly through three <fcntl.h> and <unistd.h> paths: pass O_NONBLOCK | O_CLOEXEC directly to open(), call Linux pipe2(fds, O_NONBLOCK | O_CLOEXEC) under #define _GNU_SOURCE for atomic race-free creation, or upgrade an existing descriptor via read-modify-write int fl = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, fl | O_NONBLOCK);. Always test (errno == EAGAIN || errno == EWOULDBLOCK) for strict POSIX portability.
fcntl(2) GL-C03 Quick Reference fcntl(2) NAME fcntl, pipe2 - manipulate open-file status flags or create nonblocking pipes SYNOPSIS #define _GNU_SOURCE #include <fcntl.h> #include <unistd.h> int fcntl(int fd, int cmd, ... /* arg */ ); int pipe2(int pipefd[2], int flags); DESCRIPTION F_GETFL reads access mode and struct file->f_flags status bits for fd; F_SETFL updates mutable status flags (O_NONBLOCK, O_APPEND, O_ASYNC). pipe2() atomically creates unidirectional pipe endpoints with flags applied. RETURN VALUE F_GETFL returns nonnegative status flags or -1; F_SETFL and pipe2() return 0 on success or -1 setting thread-local errno. FLAGS O_NONBLOCK Return -1 with EAGAIN/EWOULDBLOCK instead of sleeping on slow I/O. O_CLOEXEC Atomically set FD_CLOEXEC on pipe2() descriptors against execve(). ERRORS EAGAIN Nonblocking read() or write() cannot proceed immediately. EBADF fd is not a valid open file descriptor in the calling process. Kernel Systems Academy Lesson 1.1 fcntl(2) GL-C03 quick reference · full manual page: man 2 fcntl Probing Regular Files, Dynamic fcntl Flags & Nonblocking Pipes
Let us write nonblock_pipe_probe.c to verify all four kernel contracts on Linux 6.12: (1) opening a regular /tmp file with O_NONBLOCK still completes synchronous write()/read() immediately; (2) toggling a blocking pipe() endpoint via fcntl(F_GETFL) + fcntl(F_SETFL) turns an empty read() into -1 (errno == EAGAIN); (3) timing 4 back-to-back EAGAIN traps with CLOCK_MONOTONIC confirms nonzero kernel-entry cost; and (4) pipe2(..., O_NONBLOCK | O_CLOEXEC) lets an active sensor pipe (SENSOR_B:42) bypass an idle sibling pipe without stalling.
learner@ksa:~/gl-c03/m01-l01$ bat -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 47 -H 55 -H 70 -H 71 nonblock_pipe_probe.c File: nonblock_pipe_probe.c #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> static int enable_nonblock(int fd) { int flags = fcntl(fd, F_GETFL); if (flags == -1) { return -1; } return fcntl(fd, F_SETFL, flags | O_NONBLOCK); } static uint64_t mono_ns(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec; } int main(void) { const char *reg_path = "/tmp/ksa_c03_m01_l01.bin"; (void)unlink(reg_path); int rfd = open(reg_path, O_RDWR | O_CREAT | O_TRUNC | O_NONBLOCK | O_CLOEXEC, 0600); if (rfd == -1) { return EXIT_FAILURE; } char reg_buf[16] = {0}; int reg_ok = (write(rfd, "DISK_READY_16BYT", 16U) == 16 && lseek(rfd, 0, SEEK_SET) == 0 && read(rfd, reg_buf, sizeof(reg_buf)) == 16); (void)close(rfd); (void)unlink(reg_path); int dyn_pipe[2]; if (pipe(dyn_pipe) == -1) { return EXIT_FAILURE; } int before_nb = ((fcntl(dyn_pipe[0], F_GETFL) & O_NONBLOCK) != 0); if (enable_nonblock(dyn_pipe[0]) == -1) { return EXIT_FAILURE; } int after_nb = ((fcntl(dyn_pipe[0], F_GETFL) & O_NONBLOCK) != 0); char scratch[8]; errno = 0; ssize_t rc = read(dyn_pipe[0], scratch, sizeof(scratch)); int eagain_ok = (rc == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)); uint64_t t0 = mono_ns(); int spin_eagains = 0; for (int i = 0; i < 4; i++) { if (read(dyn_pipe[0], scratch, sizeof(scratch)) == -1 && errno == EAGAIN) { spin_eagains++; } } uint64_t spin_ns_per_call = (mono_ns() - t0) / 4ULL; (void)close(dyn_pipe[0]); (void)close(dyn_pipe[1]); int ch_idle[2], ch_live[2]; if (pipe2(ch_idle, O_NONBLOCK | O_CLOEXEC) == -1 || pipe2(ch_live, O_NONBLOCK | O_CLOEXEC) == -1) { return EXIT_FAILURE; } int cloexec_ok = ((fcntl(ch_live[0], F_GETFD) & FD_CLOEXEC) != 0); if (write(ch_live[1], "SENSOR_B:42", 11U) != 11) { return EXIT_FAILURE; } errno = 0; int idle_skipped = (read(ch_idle[0], scratch, sizeof(scratch)) == -1 && errno == EAGAIN); char msg[16] = {0}; ssize_t got = read(ch_live[0], msg, sizeof(msg) - 1U); (void)close(ch_idle[0]); (void)close(ch_idle[1]); (void)close(ch_live[0]); (void)close(ch_live[1]); printf("reg_ready=%d before_nb=%d after_nb=%d eagain_ok=%d spin_eagains=%d\n", reg_ok, before_nb, after_nb, eagain_ok, spin_eagains); printf("cloexec_ok=%d idle_skipped=%d live_bytes=%zd payload=%s trap_ns_pos=%d\n", cloexec_ok, idle_skipped, got, msg, spin_ns_per_call > 0ULL); return EXIT_SUCCESS; }- Read-modify-write via
F_GETFLpreserves existingstruct file->f_flagsbits such asO_APPENDwhen addingO_NONBLOCK. - Testing both
EAGAINandEWOULDBLOCKsatisfies strict POSIX portability while keeping return value0reserved forEOF. pipe2()setsO_NONBLOCKon both open-file descriptions andFD_CLOEXECon both fd table slots atomically in one syscall.
Live Linux 6.12 Execution & Syscall Trace
Compile nonblock_pipe_probe.c with -std=c11 -Wall -Wextra -Werror and inspect strace to observe fcntl(3, F_SETFL, O_RDONLY|O_NONBLOCK) flipping 0x800 and each empty read() trapping into Ring 0 to return -1 EAGAIN.
learner@ksa:~/gl-c03/m01-l01gcc -std=c11 -Wall -Wextra -Werror -fdiagnostics-color=always nonblock_pipe_probe.c -o nonblock_pipe_probelearner@ksa:~/gl-c03/m01-l01./nonblock_pipe_probereg_ready=1 before_nb=0 after_nb=1 eagain_ok=1 spin_eagains=4cloexec_ok=1 idle_skipped=1 live_bytes=11 payload=SENSOR_B:42 trap_ns_pos=1learner@ksa:~/gl-c03/m01-l01echo $?0learner@ksa:~/gl-c03/m01-l01ls -A --color=alwaysnonblock_pipe_probenonblock_pipe_probe.clearner@ksa:~/gl-c03/m01-l01learner@ksa:~/gl-c03/m01-l01strace -e \trace=openat,pipe2,fcntl,read,write,close ./nonblock_pipe_probeopenat(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) = 0openat(AT_FDCWD, "/tmp/ksa_c03_m01_l01.bin", O_RDWR|O_CREAT|O_TRUNC|O_NONBLOCK|O_CLOEXEC, 0600) = 3write(3, "DISK_READY_16BYT", 16) = 16read(3, "DISK_READY_16BYT", 16) = 16close(3) = 0pipe2([3, 4], 0) = 0fcntl(3, F_GETFL) = 0 (flags O_RDONLY)fcntl(3, F_GETFL) = 0 (flags O_RDONLY)fcntl(3, F_SETFL, O_RDONLY|O_NONBLOCK) = 0fcntl(3, F_GETFL) = 0x800 (flags O_RDONLY|O_NONBLOCK)read(3, 0x7ffe0c00c208, 8) = -1 EAGAIN (Resource temporarily unavailable)read(3, 0x7ffe0c00c208, 8) = -1 EAGAIN (Resource temporarily unavailable)read(3, 0x7ffe0c00c208, 8) = -1 EAGAIN (Resource temporarily unavailable)read(3, 0x7ffe0c00c208, 8) = -1 EAGAIN (Resource temporarily unavailable)read(3, 0x7ffe0c00c208, 8) = -1 EAGAIN (Resource temporarily unavailable)close(3) = 0close(4) = 0pipe2([3, 4], O_NONBLOCK|O_CLOEXEC) = 0pipe2([5, 6], O_NONBLOCK|O_CLOEXEC) = 0fcntl(5, F_GETFD) = 0x1 (flags FD_CLOEXEC)write(6, "SENSOR_B:42", 11) = 11read(3, 0x7ffe0c00c208, 8) = -1 EAGAIN (Resource temporarily unavailable)read(5, "SENSOR_B:42", 15) = 11close(3) = 0close(4) = 0close(5) = 0close(6) = 0write(1, "reg_ready=1 before_nb=0 after_nb"..., 138) = 138+++ exited with 0 +++Trace Dissection & Concurrency Trade-Off Comparison
Look closely at the strace log: glibc implemented pipe(dyn_pipe) via pipe2([3, 4], 0), leaving f_flags == 0 (O_RDONLY). After enable_nonblock(3) merged 0x800 (O_NONBLOCK), every subsequent empty read(3, ..., 8) still entered the kernel before returning -1 EAGAIN. In the two-channel test, read(3, ...) on ch_idle[0] returned -1 EAGAIN instantaneously (idle_skipped=1), allowing the single thread to read 11 B ("SENSOR_B:42") from ch_live[0] without any worker thread or mutex.
| I/O Architecture | Empty Stream Behavior | Idle CPU Utilization | Memory per 10,000 Streams | Primary Operational Trade-Off |
|---|---|---|---|---|
Regular disk file (S_IFREG) | Page-cache hit or block wait | 0% | ~1 KiB (struct file) | O_NONBLOCK ignored; use io_uring or pool |
| Blocking stream (1 thread total) | TASK_INTERRUPTIBLE sleep | 0% | ~1 KiB | Head-of-line stall starves sibling fds |
| Blocking stream (1 thread per fd) | Per-thread wait-queue sleep | ~0% | 80..160 MiB | Stack RAM & scheduler context-switch wall |
O_NONBLOCK + naive for (;;) | Immediate -1 (EAGAIN) | 100% | ~40 KiB | Wastes ~5M syscall traps/s when idle |
O_NONBLOCK + readiness mux | Sleeps until >= 1 fd ready | 0% | ~1..8 MiB | Production standard (poll, epoll) |
Guided & Independent Practice
Guided Practice: Nonblocking Write Saturation & Partial Drain
- Open a nonblocking pipe via
pipe2(pfd, O_NONBLOCK | O_CLOEXEC)and write4096 Bchunks intopfd[1]inside awhileloop untilwrite()returns-1(Cue 1: Linux pipes default to16pages =65,536 Bcapacity). - Verify
errno == EAGAINand record total bytes queued (Cue 2: checktotal_written == 65536on standard4 KiBpage kernels before drainingpfd[0]toEAGAIN).
Independent Practice: Dual-Channel Nonblocking Merger with Backoff Counter
Build a standalone C11 tool dual_sensor_drain.c (-std=c11 -Wall -Wextra -Werror) that spawns a fork() writer sending 20 timestamped 16 B frames across two O_NONBLOCK pipes at staggered 2 ms intervals. Count how many wasted EAGAIN syscalls your parent reader executes while collecting all 40 frames without sleeping, then compute the ratio of wasted EAGAIN traps to productive read() > 0 calls (Near transfer: increase staggered delay from 2 ms to 20 ms; Far transfer: explain why battery-powered ARMv7 gateways cannot enter CPU WFI C-states under busy-polling).
Having seen why O_NONBLOCK alone forces an ugly choice between arbitrary sleep delays and 100% CPU busy-polling, we next introduce kernel readiness multiplexing with select() and poll() so one thread sleeps at 0% idle CPU across many nonblocking streams.
Key takeaways
GL-C03(Course 3) extendsGL-C01VFS descriptors andGL-C02process/signal primitives into high-concurrency nonblocking I/O, local IPC, TCP/UDP sockets, CMake, and MQTT.- Blocking
read()suspends callers inTASK_INTERRUPTIBLEsleep (~0%CPU) when slow streams are empty, whereasO_NONBLOCKreturns-1immediately witherrno == EAGAIN/EWOULDBLOCK. - Enable
O_NONBLOCKviaopen(), atomicpipe2(fds, O_NONBLOCK | O_CLOEXEC), or read-modify-writefcntl(fd, F_GETFL)+fcntl(fd, F_SETFL, flags | O_NONBLOCK); regular disk files always remain immediately ready. - Busy-polling nonblocking descriptors in a tight
for (;;)loop burns100%CPU, requiring kernel readiness multiplexing (select,poll,epoll) to sleep efficiently across idle channels. - Blocking
read()suspends the thread inTASK_INTERRUPTIBLEsleep onp0's wait queue at ~0% CPU until bytes arrive, starving sibling descriptorp1. - Calling
F_SETFLwithout read-modify-writefcntl(fd, F_GETFL) | O_NONBLOCKclobbers existing status flags likeO_APPENDon the sharedstruct file->f_flags. - Busy-polling
O_NONBLOCKdescriptors in a tightfor (;;)loop burns 100% CPU executing millions of-1(EAGAIN) syscalls per second while idle. - Regular disk files always remain immediately ready in the Linux VFS, so
O_NONBLOCKis ignored during synchronous page-cache block reads. O_NONBLOCKresides on the sharedstruct fileopen-file description (f_flags), whereasFD_CLOEXECresides privately in each process's descriptor table slot.