Highlights

Contents

Part X
10

I/O, IPC and event loops

Devices, files and sockets all make programs wait, but the wait can block a thread or return a readiness signal. DMA moves bytes, pipes connect processes, signals report events, and event loops keep idle connections cheap. We will build from device I/O through select, poll, epoll, IPC and the server’s 1,000 descriptors.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1OS fundamentals2Processes3Fork, exec and threads4Synchronization5Deadlocks6CPU scheduling7Paging and memory8Copy-on-write9Filesystems10I/O and IPC11Protection and Linux12Complete server trace

#Section 40I/O fundamentals

Blocking describes what a calling thread does when progress is unavailable. A blocking read can sleep until bytes arrive. A non-blocking read returns immediately with a would-block result when no bytes are ready. Synchronous describes waiting for an operation’s completion, while asynchronous describes submitting work and receiving completion later. The pairs overlap but are not synonyms.

A server can use non-blocking descriptors with readiness notification, then perform short reads and writes. If the callback performs slow disk or CPU work, the event loop still stalls even though the socket is non-blocking.

BLOCKING IS ABOUT THE CALLER WAITING; ASYNC IS ABOUT HOW COMPLETION IS REPORTEDBLOCKING IS ABOUT THE CALLER WAITING; ASYNC IS ABOUT HOW COMPLETION IS REPORTEDcaller sleepscaller returns at onceblockingread() sleeps until bytes arrivez znon-blockingread() → EAGAIN, try laterEAGAINsynchronousthe call itself carries the resultasynchronoussubmit now, completion event laterwaitresult
Figure 3.53Illustrative quadrants separate caller blocking from operation completion. Orange marks immediate return, which is the key non-blocking property.

CPU-bound and I/O-bound work

CPU-bound work spends its critical time executing instructions; I/O-bound work spends much of it waiting for an external transfer. The distinction concerns the workload, not an immutable property of a process. A request can parse bytes on a core, block on storage and later resume computation. Adding threads helps only if the bottleneck and available resources permit that overlap.

Completion and caller behavior

A non-blocking read can return some bytes, end-of-file or a would-block error. Immediate return does not mean the requested application message is complete. The program must retain its parser state and wait for more readiness when needed. An asynchronous interface instead associates completion with a submitted operation. Submitting work, knowing a descriptor is ready and knowing an operation finished are different events.

#Section 41Device I/O and DMA

An application enters through a syscall, the kernel selects a driver, the controller programs a device and hardware transfers data. Direct memory access, or DMA, lets a device move bytes to or from a RAM buffer without a CPU copying every byte. Completion commonly arrives as an interrupt, after which the kernel marks a buffer or descriptor ready.

DMA still needs ownership, mapping and cache-coherence rules. The kernel must not let a device write arbitrary memory. A network packet can therefore travel from NIC to a kernel buffer, then into a socket receive queue before the application reads it.

THE CPU SETS UP THE TRANSFER; THE DEVICE MOVES THE BYTESTHE CPU SETS UP THE TRANSFER; THE DEVICE MOVES THE BYTESCPUdevice / DMAaddress + lengthbytescompletion interruptother work
Figure 3.54Illustrative DMA transfer. The CPU supplies the destination and length, the device transfers bytes to RAM, and a completion interrupt reports progress without making the CPU copy each byte.

A driver configures permitted buffers, submits device work, and handles completion or error. The CPU can work elsewhere, but consumers must wait for completed transfers and respect visibility rules.

A completion can wake a thread without immediately running its callback. Driver, protocol queues, and application reads remain separate stages with their own waits and errors.

#Section 42Blocking sockets and I/O multiplexing

Blocking and non-blocking sockets

A blocking socket can put its calling thread to sleep when bytes are absent. A non-blocking socket reports would-block instead, making waiting a separate operation. That choice belongs to the socket access path, while readiness tells the program when another attempt may be useful.

I/O multiplexing

select and poll let one thread ask about many descriptors. The kernel reports descriptors that can make progress, after which the thread performs the I/O. epoll stores interest and reports ready descriptors without requiring the application to resubmit a full set each time. Level-triggered mode reports continued readiness; edge-triggered mode reports state changes and requires draining until would-block.

Finch has 1,000 connections, 980 idle and 20 ready. The event loop can wait once and process 20 rather than scan and block on every connection. This reduces waiting overhead, but it does not make 20 expensive callbacks free.

READINESS SELECTS TWENTY SOCKETS FROM ONE THOUSAND OPEN DESCRIPTORSREADINESS SELECTS TWENTY SOCKETS FROM ONE THOUSAND OPEN DESCRIPTORS1,000 registered sockets980 idle, 20 readyready listcore 0core 1idle connections stay registered; ready work still competes for cores
Figure 3.55Computed illustrative readiness set. One thousand open descriptors include 980 idle and 20 ready descriptors; the ready list feeds work to two cores. Each dot is one descriptor.

select, poll, epoll and kqueue

select represents interest through descriptor sets with interface-specific limits. poll submits an array of descriptors and events, avoiding that particular set representation while still examining the supplied collection. Linux epoll retains an interest set and provides ready results; BSD systems provide kqueue with their own event contracts. These are interfaces with different lifecycle and registration rules, not universal promises of constant application work.

Use nonblocking operations because another consumer can remove readiness. Edge-triggered handling must drain or schedule a safe continuation, while bounding busy-socket work for fairness.

#Section 43Event loops

An event loop waits for readiness, dispatches a callback, handles timers or completions and returns to the wait. Node-style systems can keep one main language thread responsive because the thread does not sleep inside every network read. Work that blocks or runs too long needs a worker pool or another process.

The event loop is a scheduling policy layered over kernel readiness. It does not remove kernel queues, socket buffers or memory pressure. A slow callback delays unrelated connections, so bounded handler time is part of the design.

ONE THREAD, 1000 SOCKETS: EPOLL HANDS BACK THE 20 THAT ARE READYONE THREAD, 1000 SOCKETS: EPOLL HANDS BACK THE 20 THAT ARE READYepoll_wait()ready fdscallbackloopshort callbacks keepevery peer responsivesocketseach dot ≈ 20 sockets980 idle20 readya slow callback stalls all of them
Figure 3.56Illustrative event loop cycles from wait to ready descriptor to callback and back. Orange marks callback work because it is the part that can delay peers.

A ready descriptor is not itself a kernel-scheduled thread. One loop can collect Finch’s twenty ready sockets and invoke callbacks sequentially in one execution context. Parallel callback execution needs multiple schedulable threads or processes and a policy for distributing ownership. Two available cores are a machine ceiling, not evidence that one main loop automatically runs two callbacks at once.

Long handlers also delay timers and completions. A worker pool needs bounded admission, safe result ownership, and cancellation or shutdown rules for outstanding jobs.

#Section 44Pipes, shared memory and signals

A pipe is an ordered byte stream with a read end and write end. The shell can connect cat standard output to a pipe and grep standard input to the other end. Shared memory avoids repeated copying by mapping one region into multiple processes, but it needs mutexes, semaphores or atomics. A message queue preserves message boundaries through kernel-managed buffers.

Signals are small asynchronous notifications. SIGTERM can be handled, SIGKILL cannot, and SIGINT commonly comes from Ctrl+C. Signals are a poor bulk-data channel because delivery and safe handler behavior are constrained.

CAT LOG | GREP ERROR: THE SHELL WIRES ONE PROCESS'S STDOUT INTO THE NEXT ONE'S STDINCAT LOG | GREP ERROR: THE SHELL WIRES ONE PROCESS'S STDOUT INTO THE NEXT ONE'S STDIN$ cat app.log | grep ERRORcatfd 1 → write endgrepfd 0 ← read endkernel pipe buffer, 64 KiB on LinuxINFO ok\nERROR db\nfull buffer: cat blocks in write(); empty buffer: grep blocks in read()bytes, not lines: grep reassembles lines itself
Figure 3.57Illustrative pipe carries bytes from cat’s stdout to grep’s stdin. Orange marks the ordered buffer between writer and reader; the parser still needs complete lines.

IPC channels and pipes

A named pipe gives a filesystem entry for reaching a pipe-like channel. Message queues preserve message boundaries; a byte-stream pipe does not, so a reader must frame records itself. A socket can connect local processes or communicate across a network under the chosen protocol. Shared memory removes repeated transfer copies while making publication, synchronization and recovery the processes’ responsibility.

Shared memory and signals

Close unused pipe ends so readers can reach EOF. Signals report control or lifecycle events, not bulk data; handlers must obey restricted safe-operation rules rather than allocate or lock arbitrarily.