Foundations of ComputingVol. 1 · Part I
0 / 0

Shelves / Foundations of Computing

CS·08

Operating Systems

The kernel's job and how your programs live inside it: processes, threads, scheduling, concurrency primitives, virtual memory, filesystems and I/O models, with each language's view of them.

57 topics · ~69 min read · 42-question quiz
Updated Suggest a correction

Start here: what an operating system does for your program

The manager of the machine

Picture a busy restaurant kitchen with one stove, one fridge and twenty cooks who all want them at once. Without a manager there's chaos: cooks grab each other's pans, one cook hogs the stove all evening, someone opens the fridge and takes another cook's ingredients. The operating system (OS) is that manager for a computer. Linux, Windows, macOS, Android and iOS are operating systems. They do three jobs:

  1. Share the hardware among many programs: CPU time, memory, disk, network.
  2. Protect programs from each other (and the machine from programs): one buggy or malicious program shouldn't be able to crash or spy on the others.
  3. Provide convenient abstractions: instead of "write these bytes to sectors 81,920–81,927 of the disk controller", your program says "write to the file notes.txt". Files, processes, sockets and windows are all inventions of the OS.

Kernel and user space

The core of the OS is the kernel, the one program that runs with full control of the hardware. The CPU itself enforces two privilege levels:

  • Kernel mode: may do anything: talk to devices, change memory mappings, stop programs.
  • User mode: where your programs run. Attempting a privileged instruction or touching memory you don't own makes the CPU stop the program and hand control to the kernel, which usually ends it (that's what a segmentation fault is).
User space (user mode) your program browser database shell system call: openat, read, write… Kernel (kernel mode)processes · scheduler · memory · files · network · drivers · permissions Hardware: CPU cores, RAM, disk, network card, keyboard, screen
User programs ask the kernel to do privileged work through system calls

System calls: asking the kernel

Since your program can't touch the disk or network itself, it asks the kernel through a system call (syscall): a special instruction that switches the CPU into kernel mode at a fixed kernel entry point, with a number saying which service is wanted. The kernel checks the request, does the work, and returns a result. Every print, file read, network message and memory allocation that needs more memory ultimately becomes a syscall. The tool strace shows them. Here is cat /etc/hostname, with the start-up noise removed:

Text
$ strace cat /etc/hostname
openat(AT_FDCWD, "/etc/hostname", O_RDONLY) = 3
read(3, "vm\n", 131072)                 = 3
write(1, "vm\n", 3)                     = 3
read(3, "", 131072)                     = 0
close(3)                                = 0
exit_group(0)                           = ?

Read it line by line: open the file (the kernel answers with file descriptor 3, a small number meaning "your 3rd open thing"; 0, 1 and 2 are already stdin, stdout and stderr); read up to 131,072 bytes from it (got 3: vm and a newline); write those 3 bytes to descriptor 1, the screen; read again and get 0 bytes, meaning end of file; close it; exit with code 0. That's the entire program, as the kernel sees it. Even a one-line Python script that reads a file makes about 424 syscalls, mostly while the interpreter starts up. Syscalls cost far more than an ordinary function call (the switch into the kernel and back), which is why programs read and write in large buffered chunks rather than byte by byte.

Programs and processes

A program is a file on disk: instructions waiting to run. A process is a program running, with its own memory, its own open files, its own current directory and a unique process ID (PID). One program can be running as many processes at once (open three terminal windows: three bash processes). Processes form a family tree: each has a parent that started it.

On Unix, a new process is made by fork (copy the current process) and usually then exec (replace the copy's program with another one). This is how your shell runs every command:

Python
import os
print("my process id (PID):", os.getpid(), "| parent:", os.getppid())
pid = os.fork()
if pid == 0:                                   # fork returns 0 in the child…
    print(f"  child: PID {os.getpid()}, parent {os.getppid()}"); os._exit(7)
_, status = os.waitpid(pid, 0)                 # …and the child's PID in the parent
print("parent: child finished with exit code", os.waitstatus_to_exitcode(status))
Text
my process id (PID): 778 | parent: 774
  child: PID 779, parent 778
parent: child finished with exit code 7

ps lists processes, and Linux exposes each one as a folder of readable files under /proc/<PID>/:

Text
$ ps -o pid,ppid,stat,comm -p $$
  PID  PPID STAT COMMAND
  774   103 Ss   bash
$ grep -E "^(State|Threads|VmRSS)" /proc/self/status
State:	R (running)
VmRSS:	    1960 kB
Threads:	1

(VmRSS is how much physical memory the process is using: here under 2 MB.)

Taking turns: the scheduler

A machine might have 4 cores and 300 processes. Most processes are waiting (for a key press, a network message, a disk read) and need no CPU. For those that are ready to run, the kernel's scheduler gives each core to one process for a short time slice (a few milliseconds), then switches to another, many hundreds of times a second. Switching is called a context switch: the kernel saves the running process's registers (including its program counter, chapter 7) and loads another's. It happens so fast that everything seems to run at once: concurrency on one core, true parallelism across several cores.

A process's life therefore cycles among a few states: running on a core, ready (waiting for a turn), blocked (waiting for something like I/O), and finally exited.

Memory isolation: every process thinks it's alone

Each process gets its own virtual address space: a private view of memory starting from address 0. The kernel and the CPU's memory-management unit translate each process's addresses to different physical RAM, so process A's address 1000 and process B's address 1000 are different places. One process simply cannot name another's memory. The fork experiment shows it: the child's copy changes, the parent's doesn't:

Text
  child sees counter = 100
parent sees counter = 0

Virtual memory also lets the OS give processes more memory than RAM by moving rarely used parts out to disk (swapping), and share read-only parts (like library code) between processes to save space.

Threads: several workers inside one process

A thread is a separate stream of execution (its own program counter, registers and stack) inside a process. Unlike processes, threads of one process share the same memory:

Text
4 threads appended to one shared list: [0, 1, 2, 3]

Threads let one program use several cores, or wait for several things at once (a web server handling many connections). The price of sharing is danger: if two threads update the same data at the same moment, updates can be lost. That's a race condition, and avoiding it (locks, atomic operations, message passing) is a major theme of this chapter's full-depth sections and of the concurrency part of the roadmap.

Process Thread
Memory its own, isolated shared with the other threads of its process
Creating one heavier (new address space) lighter
A crash affects only that process usually brings down the whole process
Communicating through the OS: pipes, files, sockets directly through shared variables (carefully)

Files and permissions

To the OS, a file is a named sequence of bytes plus metadata: size, owner, timestamps and permissions. On Unix every file has an owner, a group, and three sets of permission bits (read r, write w, execute x) for the owner, the group, and everyone else:

Text
$ ls -l /etc/hostname /etc/shadow
-rw-r--r-- 1 root root      3 Oct 29 07:23 /etc/hostname
-rw-r----- 1 root shadow 1379 Oct 22 17:34 /etc/shadow
$ whoami; cat /etc/shadow           # as an ordinary user
postgres
cat: /etc/shadow: Permission denied

Read -rw-r--r-- as: a regular file (-), owner can read and write (rw-), group can read (r--), others can read (r--). The password-hash file /etc/shadow has --- for others, so the kernel refuses an ordinary user's openat: the check happens inside the system call, which is why programs can't skip it. These bits are where octal comes in (chapter 6): rw-r--r-- is 110 100 100 = 644; rwxr-xr-x is 755. The root user (administrator) bypasses these checks, which is why you run as an ordinary user day to day.

Check yourself

How deep to go in operating systems

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.

Level What you can do
L1 Name processes, threads, virtual memory, filesystems and system calls
L2 Use the OS correctly from code: processes, threads, files, signals, sockets
L3 Explain scheduling, context switches, synchronisation primitives, paging, page cache and I/O models
L4 Diagnose with strace, perf, /proc, vmstat, iostat: contention, page faults, fd leaks, blocking I/O
L5 Choose concurrency and I/O models, memory strategies and filesystem semantics for a service
L6 Run services on Linux at scale: limits, cgroups, kernel tuning, upgrades, noisy neighbours

What an operating system does

Kernel, user space and system calls

An operating system does three jobs:

  1. Abstraction: it turns messy hardware into clean concepts, such as files instead of disk sectors, sockets instead of NIC registers, and processes instead of raw CPU time.
  2. Multiplexing: it shares limited hardware among many programs, giving each the illusion of its own CPU, memory and devices.
  3. Isolation and protection: it stops programs (and users) from interfering with each other or with the system.

The part of the OS that runs with full hardware privilege is the kernel. CPUs enforce privilege levels: x86 has rings 0–3 (the kernel runs in ring 0 and applications in ring 3), and ARM64 has exception levels EL0–EL3. User code can't touch page tables, device registers or other processes' memory. To get anything done, it asks the kernel through a system call: a deliberate trap instruction (syscall on x86-64, svc on ARM64) that switches to kernel mode at a fixed entry point.

USER SPACE (ring 3 / EL0) your codefile.write(buf) runtime / std libbuffering, Go netpoller libc wrapperwrite(fd, p, n) syscallrax = 1 (write) KERNEL SPACE (ring 0 / EL1) entry + tablechecks args VFSfd → file object ext4 / page cache block layer + driverNVMe queue, DMA trap
A write() call travelling from your code to the device and back. Every language's I/O ends up as system calls.

A system call costs roughly 50–200 ns for the mode switch itself, more with Spectre and Meltdown mitigations, plus whatever work it does. That's why buffered I/O exists (chapter 2) and why high-performance designs batch system calls (writev, sendmmsg, io_uring). Linux exposes about 450 system calls. A few to recognise:

Area System calls
Processes fork, clone, execve, exit_group, wait4, kill
Files openat, read, write, close, lseek, fstat, fsync, rename
Memory mmap, munmap, mprotect, brk, madvise
Network socket, bind, listen, accept4, connect, sendto, recvfrom
Event I/O epoll_create1, epoll_ctl, epoll_wait, io_uring_setup, io_uring_enter
Sync futex (the basis of all Linux mutexes)

strace -f ./program prints every system call a program makes, and it's one of the best debugging tools there is. strace -c gives counts and time per call.

Kernel designs

  • Monolithic kernels (Linux, the BSDs) put filesystems, drivers, networking and scheduling in one privileged address space. They're fast (subsystems call each other directly) but a bug in any driver can crash or compromise the whole system. Linux reduces the risk with loadable modules and, more recently, eBPF: small verified programs loaded into the kernel for tracing, networking and security without writing kernel modules.
  • Microkernels (seL4, QNX, MINIX 3) keep only minimal mechanisms in the kernel (address spaces, threads, IPC) and run drivers and filesystems as user processes. They're more robust and verifiable (seL4 is formally proved correct), but pay for extra IPC.
  • Hybrid kernels (Windows NT, macOS XNU) mix the two in practice.
  • Unikernels compile one application together with just the OS pieces it needs into a single image, for specialised cloud workloads.

Processes

What a process is

A process is a program in execution: the OS's unit of isolation and resource ownership. A process has:

  • A virtual address space: its own private view of memory (code, data, heap, stacks, mapped files).
  • One or more threads of execution.
  • Resources: open file descriptors, sockets, signal handlers, current directory, environment variables, resource limits.
  • Credentials: user and group IDs and capabilities, which determine what it's allowed to do.
  • Kernel bookkeeping in a process control block (task_struct in Linux, about 10 KB).

The standard virtual memory layout of a Linux process (high addresses at the top):

Text
0x7fff_ffff_ffff ┌──────────────────────────┐
                 │ stack (main thread)       │ ↓ grows down; 8 MB limit by default
                 │ … guard page …            │
                 │ mmap region               │ shared libraries (libc.so), mmap'd files,
                 │                           │ thread stacks, large malloc blocks
                 │ … free …                  │
                 │ heap                      │ ↑ grows up (brk); small malloc blocks
                 │ .bss  (zeroed globals)    │
                 │ .data (initialised globals)│
                 │ .text (machine code, r-x) │
0x0000_0040_0000 └──────────────────────────┘   (with ASLR, all bases are randomised)

You can view a live process's map with cat /proc/<pid>/maps or pmap <pid>.

PIDs and the process tree

Every process has a numeric process ID (PID). On Linux each thread also has an ID (TID). The main thread's TID equals the PID, and getpid() returns the same value in every thread. PID 1 is init (usually systemd), the ancestor of all user processes. In a container, the first process gets PID 1 inside its PID namespace. That has consequences covered below.

ps -ef --forest, pstree -p and /proc/<pid>/status show the tree, and top/htop show resource use.

Parent and child: fork, exec and wait

Unix creates processes in two steps that are separate on purpose:

  1. fork() duplicates the calling process. The child gets a copy of the parent's address space, file descriptors and everything else. fork returns twice: 0 in the child and the child's PID in the parent. Copying gigabytes would be slow, so the kernel uses copy-on-write (COW): parent and child share the physical pages read-only, and a page is copied only when one of them writes to it.
  2. execve(path, argv, envp) replaces the current process image with a new program. The PID and open file descriptors (unless marked close-on-exec) are kept.
  3. The parent calls wait()/waitpid() to collect the child's exit status.

The gap between fork and exec is where a shell sets up redirections, pipes and environment variables for the child. It's an elegant design, and the reason cmd > out.txt 2>&1 | grep x is easy to implement (it's roadmap project 2).

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {                                // child
        execlp("ls", "ls", "-l", (char *)NULL);    // replaces the child's program
        perror("exec");                            // only reached if exec failed
        _exit(127);
    }
    int status;
    waitpid(pid, &status, 0);                      // parent: reap the child
    if (WIFEXITED(status)) printf("child exited with %d\n", WEXITSTATUS(status));
    return 0;
}

Zombies and orphans. A child that has exited but hasn't been waited for stays as a zombie (state Z in ps). Its memory is freed, but its PID and exit status are kept for the parent. Many zombies can exhaust the PID space. If the parent dies first, the child becomes an orphan and is re-parented to PID 1, which reaps it. In a container, your program might be PID 1, and a naive PID 1 doesn't reap zombies or forward signals properly. That's why images use tini or dumb-init (Docker --init), and why docker stop can sometimes take 10 seconds and end in SIGKILL (Part VI).

Process states

A process (strictly, each thread) moves between states:

New Ready Running Blocked Terminated admit scheduled preempted / yield wait (I/O, lock, sleep) event done exit
Process/thread state machine. Only the scheduler moves a thread between Ready and Running.

Linux's ps codes are R (running or runnable), S (interruptible sleep: waiting on an event), D (uninterruptible sleep, usually in-flight disk or NFS I/O, which even SIGKILL can't interrupt), T (stopped, for example by Ctrl-Z or a debugger), and Z (zombie). The Linux load average counts R and D tasks, so a high load can mean slow disks rather than busy CPUs.

Scheduling

The scheduler decides which ready thread runs on each core, and for how long. Its goals conflict: throughput (finish as much work as possible), latency and responsiveness (interactive work runs promptly), fairness, and efficiency (keep caches warm and save power).

Classic policies:

Policy Idea Weakness
FCFS (first come, first served) Run in arrival order until done One long job blocks short ones (the convoy effect)
SJF / SRTF Shortest job (remaining time) first: optimal average waiting time Needs to know job lengths; long jobs can starve
Round robin Each thread gets a time slice (quantum) in turn Slice too short: switching overhead. Too long: poor latency
Priority Highest priority runs first Starvation, unless priorities age upward over time
MLFQ (multi-level feedback queue) Threads that use their whole slice drop in priority; ones that block early (interactive) stay high Tuning; gaming by apps
Fair / proportional share Each thread gets CPU in proportion to its weight Bookkeeping cost

Linux used CFS (Completely Fair Scheduler) from 2007 until kernel 6.6 (2023), when it was replaced by EEVDF (Earliest Eligible Virtual Deadline First). Both track each task's virtual runtime (CPU time scaled by its weight, which comes from the nice value −20…19) and keep runnable tasks ordered in a red-black tree (chapter 3), always running the task that has had the least. EEVDF adds deadlines so latency-sensitive tasks get shorter slices sooner. Linux also has real-time classes (SCHED_FIFO, SCHED_RR) for strict priorities, and SCHED_DEADLINE. Since 6.12, sched_ext lets schedulers be written as eBPF programs.

Scheduling in containers works differently. Kubernetes CPU limits are enforced by the CFS bandwidth controller (cgroup cpu.max): a container may use quota microseconds of CPU per period (100 ms by default). A multithreaded app can burn its whole quota in 20 ms and then be throttled for 80 ms, a latency spike with the CPU otherwise idle. JVM and Go services hit this often. Mitigations include sizing thread pools to the CPU limit (-XX:ActiveProcessorCount, and Go's GOMAXPROCS, which became cgroup-aware in Go 1.25), and being careful about setting CPU limits on latency-critical services at all (Part VI).

Context switches

A context switch saves the current thread's state (registers, stack pointer, instruction pointer, FPU and vector registers) and restores another's. If the new thread belongs to a different process, the switch also changes the address space (the page-table root, CR3 on x86), which can flush or tag TLB entries.

  • Direct cost: about 1–5 µs on modern Linux, including the kernel entry and exit.
  • Indirect cost, often larger: the new thread finds cold caches, TLB and branch predictor state. Heavy context switching shows up as low IPC.
  • Voluntary switches happen when a thread blocks (I/O, a lock, sleep). Involuntary switches happen when it's preempted (slice expired, higher priority woke up). pidstat -w or /proc/<pid>/status (voluntary_ctxt_switches) show both.

Context switches cost a few microseconds each. A server with 10,000 OS threads blocking and waking can spend a large share of its time switching. That's the main motivation for event loops, async/await, and user-space threads (goroutines, Java virtual threads), whose switches happen in user space in roughly 100–200 ns without entering the kernel.

Signals

A signal is an asynchronous notification delivered to a process. It's a software interrupt for user space. When one arrives, the kernel interrupts the target thread and runs its handler, or applies the default action.

Signal Default Typical meaning
SIGINT (2) terminate Ctrl-C
SIGTERM (15) terminate "Please shut down" (kill, docker stop, Kubernetes pod termination)
SIGKILL (9) terminate Immediate death. Can't be caught or ignored
SIGSTOP / SIGTSTP stop Pause (uncatchable / Ctrl-Z)
SIGCONT continue Resume
SIGHUP (1) terminate Terminal closed; by convention "reload config" for daemons (Nginx)
SIGCHLD ignore A child changed state: time to wait
SIGSEGV (11) core dump Invalid memory access
SIGPIPE terminate Wrote to a pipe or socket whose reader has gone (servers usually ignore it and handle EPIPE)
SIGUSR1 / SIGUSR2 terminate Application-defined

Graceful shutdown follows from the table. Kubernetes sends SIGTERM, waits terminationGracePeriodSeconds (30 s by default), then sends SIGKILL. A well-behaved service catches SIGTERM, stops accepting new work, finishes in-flight requests, flushes buffers, closes connections, and exits. Each language exposes it:

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
srv := &http.Server{Addr: ":8080"}
go func() { _ = srv.ListenAndServe() }()
<-ctx.Done()                                            // wait for the signal
shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
_ = srv.Shutdown(shutdownCtx)                           // drain in-flight requests

Signal handlers interrupt your code at arbitrary points, possibly inside malloc or while a lock is held. In a handler, only async-signal-safe functions are allowed (write, _exit, setting a volatile sig_atomic_t). The robust patterns are: set a flag; write a byte to a "self-pipe" that the main loop watches; or receive signals synchronously through signalfd or sigwait in a dedicated thread. That's what Go, Rust tokio and the JVM do internally.

Threads

Threads versus processes

A thread is an independent flow of execution inside a process. Threads of one process share the address space (heap, globals, code), open files, and signal handlers. Each thread has its own stack, registers and instruction pointer, thread-local storage, and signal mask.

Processes Threads
Memory Isolated (separate address spaces) Shared
Creation cost Higher (new address space, even with COW) Lower (~10–20 µs for an OS thread)
Communication IPC: pipes, sockets, shared memory, files Just read and write shared variables, with synchronisation
Failure isolation A crash kills one process A crash (segfault, unhandled panic) usually kills the whole process
Security boundary Yes No

On Linux, both are created with clone() with different flags. A thread is a task that shares the memory and file table. Browsers use processes for isolation (one renderer per site, chapter 18). Databases differ: PostgreSQL uses a process per connection, while MySQL uses threads. Application servers use threads, or lightweight user-space threads.

User threads, kernel threads and M:N scheduling

  • Kernel (OS) threads are known to and scheduled by the kernel: Java platform threads, C++ std::thread, Rust std::thread, Zig std.Thread, and pthreads. They can run truly in parallel on multiple cores, and blocking one doesn't block the others. Each needs a kernel object plus a fixed stack (default about 8 MB of virtual memory on Linux, committed lazily). Creation and context switches go through the kernel. Practical limits are in the thousands to tens of thousands per process.
  • User (green) threads are scheduled by a runtime inside the process. Creating and switching them are cheap user-space operations, and stacks can be small and growable.

Mapping models:

Model Mapping Examples Trade-off
1:1 each user thread is a kernel thread Java platform threads, pthreads, Rust/C++/Zig std threads Simple, parallel, but heavy
N:1 many user threads on one kernel thread Early Java "green threads", Python's GIL-bound async, Node.js callbacks Cheap, but no parallelism, and one blocking call blocks everyone
M:N many user threads multiplexed over a pool of kernel threads Go goroutines, Java virtual threads (JDK 21), Erlang processes, Tokio tasks (with async) Cheap and parallel. The runtime must handle blocking system calls

Go's scheduler uses the G-M-P model: G is a goroutine, M is an OS thread ("machine"), and P is a processor context, with GOMAXPROCS of them (one per core by default). Each P has a local run queue of goroutines and steals from others when idle (work stealing). Goroutine stacks start at about 2 KB and grow by copying. When a goroutine makes a blocking system call, its M is parked and the P moves to another M, so other goroutines keep running. Network I/O never blocks an M at all: the netpoller (epoll, kqueue or IOCP) parks the goroutine and wakes it when the socket is ready. Preemption is asynchronous via signals (since Go 1.14), so tight loops can't hog a P.

Java virtual threads (JEP 444, JDK 21) are scheduled by a ForkJoinPool of carrier platform threads. When a virtual thread blocks in JDK I/O, sleep, or java.util.concurrent locks, it unmounts: its stack frames are copied to the heap, and the carrier runs another virtual thread. You write ordinary blocking code, and the runtime turns it into event-driven scheduling. One historical catch was pinning: blocking inside a synchronized block kept the carrier thread occupied. JDK 24 removed most of that limitation (JEP 491). Native calls through JNI or FFM can still pin.

Rust async is another approach entirely. async fn compiles into a state machine (a Future) with no separate stack. An executor such as Tokio polls futures on a thread pool, and they suspend at .await points. It's very memory-efficient, but blocking inside async code stalls the executor thread (use spawn_blocking), and async "colours" functions: async functions can only be awaited from other async code. Zig is redesigning its I/O around an Io interface that callers pass in. The same code can then run on blocking threads, an event loop, or green threads, which avoids function colouring.

Shared memory between threads

Threads communicate by reading and writing shared memory. That's fast and convenient, and it's the source of the hardest bugs in programming, for three reasons:

  1. Interleaving: the scheduler can switch threads between any two instructions, and on multicore machines threads truly run simultaneously.
  2. Non-atomic operations: counter++ is three steps (load, add, store). So is updating a 64-bit value on some 32-bit platforms, or a Go interface or slice header (several words).
  3. Visibility and reordering: without synchronisation, the compiler may keep a value in a register, and the CPU may reorder memory operations (chapter 7). One thread's write may never become visible to another, or may become visible out of order.

Memory models define exactly when a write by one thread is guaranteed visible to a read by another. The central concept, shared by Java, C++, Rust, Go and Zig, is happens-before: if action A happens-before action B, then B sees A's effects. Happens-before edges come from synchronisation: unlocking a mutex happens-before the next lock of it, a release-store happens-before an acquire-load that reads it, starting a thread happens-before its first action, and a thread finishing happens-before join returns. Two conflicting accesses (at least one a write) that aren't ordered by happens-before form a data race.

Consequence of a data race
C / C++ Undefined behaviour
Rust Impossible in safe code (Send/Sync + borrowing). unsafe races are UB
Zig Illegal behaviour (unchecked)
Java Defined but weak: you may see stale or unexpected values, but no out-of-thin-air values and no memory corruption
Go Mostly like Java, but races on multi-word values (interfaces, slices, strings, maps) can corrupt memory and crash. Detect them with -race

Thread lifecycle

Creating, running and joining threads in each language:

Thread t = Thread.ofPlatform().name("worker").start(() -> System.out.println("hi"));
t.join();                                       // wait for it to finish
Thread v = Thread.ofVirtual().start(() -> doBlockingIo());   // JDK 21+
v.join();
// Prefer executors over raw threads:
try (var exec = Executors.newFixedThreadPool(4)) {
    Future<Integer> f = exec.submit(() -> 6 * 7);
    System.out.println(f.get());
}   // ExecutorService is AutoCloseable since JDK 19: close() waits for tasks

Thread pools reuse a fixed set of threads for many short tasks, avoiding creation costs and bounding concurrency. Size them by workload: about the number of cores for CPU-bound work, and more for blocking I/O. Virtual threads and goroutines remove most of the need to pool for I/O-bound work. You still bound concurrency to protect downstream resources such as database connection limits, using a semaphore. Roadmap project 4 is building a thread pool.

Concurrency

Race conditions

A race condition is a bug where correctness depends on the timing or interleaving of concurrent operations. The classic example is two threads incrementing a shared counter:

Text
counter = 5
Thread A: load counter (5)
                               Thread B: load counter (5)
Thread A: add 1 → 6
                               Thread B: add 1 → 6
Thread A: store 6
                               Thread B: store 6            → counter = 6, one increment lost

Run a million increments in each of two threads without synchronisation and you'll typically get a total well below two million, different on every run. Note two distinct concepts:

  • A data race is a low-level memory-model violation: unsynchronised conflicting accesses.
  • A race condition is a higher-level logic bug. You can have one without a data race. "Check then act" is the typical case: if (!map.containsKey(k)) map.put(k, v) on a ConcurrentHashMap has no data race, because each call is thread-safe, but two threads can both see "absent" and both insert. Use the atomic putIfAbsent/computeIfAbsent. The same pattern causes TOCTOU (time-of-check to time-of-use) security bugs: check a file's permissions, then open it, while an attacker swaps in a symlink between the two steps.

Races are hard to debug because they're non-deterministic: they may happen once in a million runs, only under load, or only on ARM. Tools help: Go's -race, ThreadSanitizer (-fsanitize=thread for C, C++, Rust and Zig), Java's jcstress for testing concurrency semantics, and loom or shuttle in Rust for exhaustively exploring interleavings.

Critical sections and atomicity

A critical section is code that accesses shared state and must not run in more than one thread at a time. A correct solution to the critical-section problem gives:

  1. Mutual exclusion: at most one thread inside.
  2. Progress: if no one is inside, someone who wants in eventually gets in.
  3. Bounded waiting: no thread waits forever while others repeatedly enter (fairness).

Hardware provides the building blocks as atomic instructions: read-modify-write operations that no other core can interrupt halfway.

  • Compare-and-swap (CAS): "if the value at address X equals expected, set it to new, and tell me whether it worked." On x86 it's lock cmpxchg. ARM64 uses ldxr/stxr (load-linked/store-conditional) loops, or the LSE cas instruction.
  • Fetch-and-add: lock xadd, ARM ldadd.
  • Atomic load and store with ordering constraints (acquire/release/sequentially consistent).

Atomics enable lock-free algorithms: retry a CAS until it succeeds, so no thread ever holds a lock. Java's AtomicLong, ConcurrentLinkedQueue and ConcurrentHashMap (partly) work this way, as do Rust's crossbeam and std::sync::atomic, Go's sync/atomic, C++ std::atomic, and Zig's std.atomic.Value.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;

let counter = Arc::new(AtomicU64::new(0));
let handles: Vec<_> = (0..4).map(|_| {
    let c = Arc::clone(&counter);
    thread::spawn(move || for _ in 0..1_000_000 { c.fetch_add(1, Ordering::Relaxed); })
}).collect();
for h in handles { h.join().unwrap(); }
assert_eq!(counter.load(Ordering::Relaxed), 4_000_000);   // always correct
// Relaxed is fine for a pure counter; use Acquire/Release when the atomic
// *publishes* other data (a "ready" flag guarding a buffer).

Mutex

A mutex (mutual exclusion lock) is the basic tool. lock() blocks until the caller holds it, and unlock() releases it. Only the holder may unlock. Linux mutexes are built on futexes ("fast userspace mutexes"). The uncontended path is a single atomic CAS in user space, about 20 ns. Only when there's contention does the thread make a futex system call to sleep in the kernel. Many implementations spin briefly before sleeping, betting the holder will release soon.

The languages wrap mutexes very differently, and the design differences matter:

use std::sync::{Arc, Mutex};
use std::thread;

// The Mutex OWNS the data. You literally cannot touch the Vec without locking.
let shared = Arc::new(Mutex::new(Vec::new()));
let hs: Vec<_> = (0..4).map(|i| {
    let s = Arc::clone(&shared);
    thread::spawn(move || {
        let mut guard = s.lock().unwrap();   // MutexGuard: derefs to &mut Vec
        guard.push(i);
    })                                       // guard dropped → unlocked (RAII)
}).collect();
for h in hs { h.join().unwrap(); }
// lock() returns Err if a thread panicked while holding it ("poisoning").

Rust's design, where the lock contains the data it protects, makes "forgot to lock" a compile error. Everywhere else, the association between a lock and its data is a comment or a convention, checked at best by annotations (Clang's GUARDED_BY thread-safety analysis, Java's @GuardedBy, used only by tools).

Reentrancy: Java's synchronized and ReentrantLock are reentrant: the holding thread can lock again, and must unlock as many times. Go's sync.Mutex, Rust's Mutex, C++'s std::mutex and Zig's Mutex are not. Locking twice from the same thread deadlocks. That's deliberate, since reentrant locking often hides confused invariants.

Reader-writer locks (RwLock, ReadWriteLock, sync.RWMutex, std::shared_mutex) allow many readers or one writer. They help when reads dominate and the critical sections are long. With short critical sections, their extra bookkeeping can make them slower than a plain mutex.

Semaphore

A semaphore (Dijkstra, 1965) is a counter with two atomic operations: wait/P/acquire decrements it, blocking while it's 0, and signal/V/release increments it, waking a waiter. A binary semaphore (0 or 1) works like a lock, though it has no notion of an owner. A counting semaphore limits concurrency to N, which is the most common use today:

Java
Semaphore dbPermits = new Semaphore(20);       // at most 20 concurrent DB calls
void query() throws InterruptedException {
    dbPermits.acquire();
    try { runQuery(); } finally { dbPermits.release(); }
}

In Go, a buffered channel is the idiomatic semaphore (sem := make(chan struct{}, 20), then sem <- struct{}{} to acquire and <-sem to release), or use golang.org/x/sync/semaphore. Tokio has tokio::sync::Semaphore, C++20 has std::counting_semaphore, and POSIX has sem_t. Bulkheads, rate limiters and connection pools (Part III) are all semaphores at heart.

Monitors and condition variables

Mutual exclusion isn't enough when a thread must wait for a condition: a queue becoming non-empty, a buffer gaining space, a job finishing. Busy-waiting (while (queue.isEmpty()) {}) burns CPU. A condition variable lets a thread atomically release a lock and sleep until another thread signals that the condition may have changed.

A monitor (Hoare and Brinch Hansen, 1970s) bundles a mutex, the data it protects, and condition variables. Every Java object is a monitor: synchronized plus wait()/notify()/notifyAll().

The canonical bounded buffer (producer–consumer) shows the pattern, and it has two rules that must never be broken:

  1. Always wait in a while loop that rechecks the condition, never an if. Wakeups can be spurious (the OS can wake a thread for no reason), and another thread may consume the item between the signal and your wakeup.
  2. Change the condition and signal while holding the lock (or at least change it under the lock), so no wakeup is lost.
final class BoundedBuffer<T> {
    private final Object[] items;
    private int head, tail, count;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    BoundedBuffer(int capacity) { items = new Object[capacity]; }

    void put(T x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) notFull.await();   // WHILE, not if
            items[tail] = x; tail = (tail + 1) % items.length; count++;
            notEmpty.signal();
        } finally { lock.unlock(); }
    }

    @SuppressWarnings("unchecked")
    T take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) notEmpty.await();
            T x = (T) items[head]; items[head] = null; head = (head + 1) % items.length; count--;
            notFull.signal();
            return x;
        } finally { lock.unlock(); }
    }
}
// In real code: ArrayBlockingQueue / LinkedBlockingQueue already do exactly this.

Deadlock

A deadlock is a set of threads each waiting for a resource another one holds, so none can ever proceed. Coffman (1971) showed that deadlock requires all four of these conditions at once:

  1. Mutual exclusion: resources can't be shared.
  2. Hold and wait: a thread holds one resource while waiting for another.
  3. No preemption: resources can't be forcibly taken away.
  4. Circular wait: a cycle exists in the "waits-for" graph.

The textbook case is two threads locking two accounts for a transfer, in opposite orders:

Text
Thread 1: transfer(A → B): lock(A) … lock(B)   ← waits for B
Thread 2: transfer(B → A): lock(B) … lock(A)   ← waits for A          → deadlock

Break any one condition to prevent it:

Strategy Breaks How
Global lock ordering Circular wait Always lock in a fixed order (by account ID or memory address). This is the most common practical fix
Lock several at once Hold and wait C++ std::scoped_lock(a, b) uses a deadlock-avoidance algorithm. Or use one coarser lock
tryLock with timeout and backoff No preemption Java tryLock(100, ms), then release everything and retry
Avoid shared locks Mutual exclusion Message passing, immutable data, a single owner thread (actor)
Detection and recovery — Databases build the waits-for graph, find cycles (chapter 4's cycle detection), and abort a victim transaction. That's what deadlock detected means in PostgreSQL
Rust
fn transfer(from: &Account, to: &Account, amount: u64) {
    // order locks by a stable key to avoid circular wait
    let (first, second) = if from.id < to.id { (from, to) } else { (to, from) };
    let mut a = first.balance.lock().unwrap();
    let mut b = second.balance.lock().unwrap();
    // … move money between *a and *b according to direction …
}

To diagnose a live deadlock: jstack <pid> prints Java threads and reports detected deadlocks explicitly. In Go, SIGQUIT (Ctrl-) dumps all goroutine stacks, and the runtime aborts with "all goroutines are asleep - deadlock!" when everything is blocked. For C, C++, Rust and Zig, attach gdb and run thread apply all bt.

Livelock and starvation

  • Livelock: threads keep changing state in response to each other without making progress, like two people in a corridor who both step aside the same way, repeatedly. Typical cause: two threads that both back off and retry in lockstep. The fix is randomised backoff (jitter), the same idea as Ethernet's exponential backoff and the jittered retries in Part III.
  • Starvation: a thread is ready but never gets the resource, because others keep winning: low-priority threads under priority scheduling, writers starved by a continuous stream of readers on some reader-writer locks, or an unfair lock that keeps handing ownership to the thread that just released it. Fixes include fair locks (new ReentrantLock(true) grants in FIFO order, at a throughput cost), priority aging, and writer-preferring RW locks.
  • Priority inversion: a high-priority task waits for a lock held by a low-priority task, which is itself preempted by a medium-priority task. The high-priority task is effectively blocked by the medium one. This famously reset the Mars Pathfinder lander repeatedly in 1997. Priority inheritance (the lock holder temporarily inherits the waiter's priority) fixes it, and JPL enabled it by remote patch.

Memory management

Virtual memory

Chapter 7 covered the hardware: the MMU translates every virtual address through page tables, cached in the TLB. Here is what the OS does with that. Virtual memory gives each process the illusion of a large, private, contiguous address space, and gives the OS several powers:

  • Isolation: process A's address 0x1000 and process B's address 0x1000 map to different physical frames. One process can't even name another's memory.
  • Protection: per-page permissions. Code is read+execute, data is read+write with no execute (NX/W^X, which defeats simple code injection), and the kernel's pages are inaccessible from user mode.
  • Overcommit and lazy allocation: malloc(1 GB) returns instantly, and physical frames are assigned only when pages are first touched.
  • Sharing: one physical copy of libc.so's code is mapped into every process. Copy-on-write after fork. Shared memory for IPC.
  • Memory-mapped files: file contents appear as memory (mmap, below).
  • Paging to disk: rarely used pages can be swapped out to make room.
  • ASLR: randomising where the stack, heap, libraries and executable are placed makes exploits much harder.

Pages and page tables

Memory is managed in pages (virtual) mapped to frames (physical), normally 4 KB. ARM64 can also use 16 KB or 64 KB base pages, and Apple Silicon uses 16 KB. Each process has its own page table, a radix tree indexed by bits of the virtual address (4 levels on x86-64, chapter 7). Each page table entry (PTE) holds the frame number plus flags:

Flag Meaning
Present Mapped to a frame right now (if clear, an access faults)
Writable Writes allowed
User Accessible from user mode
NX (no-execute) Instructions can't be fetched from it
Accessed / Dirty Set by hardware on read / write. The OS uses them to pick pages to evict, and to know which pages must be written back

Why a multi-level tree instead of one flat table? A flat table for a 48-bit space with 4 KB pages would need 2³⁶ entries (512 GB) per process. With a tree, untouched regions cost nothing, because whole subtrees are simply absent.

Huge pages (2 MB or 1 GB on x86-64) map a large region with one TLB entry. A TLB with about 1,500 entries covers only about 6 MB with 4 KB pages, but 3 GB with 2 MB pages. Databases (PostgreSQL huge_pages, Oracle), JVMs (-XX:+UseLargePages, -XX:+UseTransparentHugePages), and DPDK benefit. Linux's Transparent Huge Pages (THP) does this automatically, but its background compaction has caused latency spikes, so Redis and MongoDB have historically recommended setting THP to madvise or never.

TLB behaviour

The TLB caches recent translations (chapter 7). Things the OS must manage:

  • On a context switch between processes, the TLB contents belong to the wrong address space. Older CPUs flushed the entire TLB. Modern CPUs tag entries with an address-space ID (PCID on x86, ASID on ARM), so entries survive the switch.
  • When the kernel changes a mapping (munmap, mprotect, page migration), every core that might cache it must invalidate its entry. That's done by sending inter-processor interrupts: a TLB shootdown. Frequent mmap/munmap in a heavily multithreaded program can become a scalability bottleneck because of this.
  • Programs whose working set spans many pages randomly (large hash tables, graph analytics, big JVM heaps) suffer TLB misses on top of cache misses. Huge pages are the main remedy.

Page faults

A page fault is the MMU trapping into the kernel because a translation is missing or the access isn't permitted. The kernel then decides what kind of fault it is:

Kind Cause Kernel action Cost
Minor (soft) Page is in RAM but not mapped for this process: first touch of a lazily allocated page, a shared library page already cached, copy-on-write Allocate or zero a frame, or copy it (COW), or map the existing page ~0.1–1 µs
Major (hard) Page must be read from disk: a swapped-out page, or an mmaped file page not in the page cache Block the thread, issue I/O, map the page when it arrives ~10 µs (NVMe) to ~10 ms (HDD)
Invalid Address not mapped at all, or permission violated (writing to read-only, executing NX) Send SIGSEGV (segmentation fault), or SIGBUS for some mmap errors Process usually dies

Viewing them: /usr/bin/time -v ./prog reports minor and major faults, perf stat -e page-faults counts them, and ps -o min_flt,maj_flt. Many major faults on a service means it's swapping, or reading mmap'd data that's cold.

Swapping and the OOM killer. When RAM runs out, Linux first reclaims the page cache (clean file pages can simply be dropped, and dirty ones written back), then swaps out anonymous memory if swap exists. If it still can't satisfy allocations, the OOM killer chooses a process (by oom_score, mostly by memory size) and sends it SIGKILL. In containers, the same thing happens per cgroup when the memory limit is hit: the container is killed with exit code 137 (128 + SIGKILL's 9), status OOMKilled. For JVMs this often means the heap was fine, but heap plus metaspace plus thread stacks plus direct buffers plus GC overhead exceeded the limit. Size -XX:MaxRAMPercentage (default 25%; commonly set to 60–75%) with that in mind (Part III, chapter 40).

Heap and stack

These are two regions of virtual memory with completely different management:

Stack Heap
Holds Function frames: locals, return addresses, saved registers Dynamically allocated objects whose size or lifetime isn't fixed at compile time
Allocation Move the stack pointer: about 1 instruction Ask an allocator (malloc, new, GC). From ~20 ns up to µs when it needs a system call
Freeing Automatic on return Manual (free), RAII, reference counting, or GC (chapter 2)
Size Small and fixed per thread: 8 MB main thread on Linux, often 1–2 MB for others, kilobytes for goroutines (growable) Large: limited by address space and RAM
Locality Excellent (always hot in cache) Depends on the allocator and access pattern
Failure Stack overflow (deep recursion, huge local arrays) Out of memory; fragmentation
Shared between threads? No (each thread has its own) Yes

How malloc works (roadmap project 1 is building one). The allocator gets large regions from the OS: brk/sbrk grows the heap segment, and mmap maps anonymous pages (used for large blocks, above 128 KB in glibc). It then hands out small pieces. It keeps free lists of blocks grouped by size class and splits and coalesces blocks. Modern allocators (jemalloc, used by Redis and historically by Rust; tcmalloc, Google's; mimalloc, Microsoft's; glibc's ptmalloc2) use per-thread caches and arenas to avoid lock contention. Switching allocators can cut memory use or latency noticeably in multithreaded services, so it's worth benchmarking.

Fragmentation: external fragmentation means free memory is split into pieces too small to use. Internal fragmentation means allocated blocks are larger than requested (size-class rounding). Long-running C, C++ and Rust services can see resident memory grow slowly from fragmentation even without leaks. Compacting garbage collectors (Java's G1 and ZGC, chapter 40) avoid external fragmentation by moving live objects together. Go's GC doesn't move objects. It relies on size-segregated spans instead.

Allocators per language: C has malloc/free. C++ has new/delete and std::pmr memory resources (arenas and pools). Rust has the GlobalAlloc trait, with Box, Vec and others using the global allocator (you can swap it with #[global_allocator] for jemalloc or mimalloc), and the Allocator trait for per-collection allocators is still unstable. Zig makes allocators explicit parameters everywhere: std.heap.page_allocator, ArenaAllocator (free everything at once, ideal per request), FixedBufferAllocator (no heap at all), DebugAllocator (leak detection), and smp_allocator. Java and Go allocate from the GC heap, where allocation is just a pointer bump in a thread-local allocation buffer (TLAB in the JVM, the mcache in Go). That's often faster than malloc, and the cost is paid later by the collector.

mmap and memory-mapped files

mmap asks the kernel to map something into your address space:

  • Anonymous mappings: zero-filled memory with no file behind it. Allocators use them for large blocks, and threads use them for stacks.
  • File mappings: a file's contents appear as an array of bytes in memory. The first access to each page triggers a page fault, and the kernel loads it from the page cache. Writes to a MAP_SHARED mapping go back to the file (eventually, or on msync). MAP_PRIVATE gives copy-on-write.
  • Shared mappings between processes: the fastest IPC, since both processes see the same physical pages.
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char **argv) {
    int fd = open(argv[1], O_RDONLY);
    struct stat st; fstat(fd, &st);
    const char *p = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (p == MAP_FAILED) { perror("mmap"); return 1; }
    long lines = 0;
    for (off_t i = 0; i < st.st_size; i++) lines += p[i] == '\n';   // just read memory
    printf("%ld\n", lines);
    munmap((void *)p, st.st_size);
    close(fd);
}

When mmap helps: random access into large files, sharing read-only data between processes (several processes mapping the same model weights or index), and zero-copy parsing. Users include LMDB, SQLite (optionally), MongoDB's old MMAPv1 engine, Lucene and Elasticsearch index files, Kafka's index files, and loading ML model weights (llama.cpp mmaps GGUF files).

When it hurts: errors arrive as SIGBUS instead of error codes (for example, the file was truncated or the disk failed). Page faults block the thread unpredictably, which is bad in async runtimes. And the database can't control eviction, flushing order or I/O scheduling. The well-known CIDR 2022 paper "Are You Sure You Want to Use MMAP in Your Database Management System?" argues most databases should manage their own buffer pool (chapter 58).

Filesystems

Files, file descriptors and the VFS

To a program, a file is a named sequence of bytes with metadata. The OS gives each open file a small integer handle, the file descriptor (fd), which indexes the process's file descriptor table. 0, 1 and 2 are stdin, stdout and stderr. In Unix, "everything is a file": regular files, directories, pipes, sockets, terminals, devices (/dev/null, /dev/nvme0n1), and kernel interfaces (/proc, /sys) are all reached through the same open/read/write/close calls.

Three layers of tables are involved:

Text
process fd table          system-wide open file table         inode
fd 3 ───────────────────▶ { offset: 4096, flags: O_RDONLY } ──▶ { size, owner, mode, blocks… }
fd 4 ─┐                                                    ┌─▶
      └─(dup2 / fork)───▶ { offset: 0, flags: O_WRONLY  } ─┘     (same inode, two opens)

So after fork, parent and child share file offsets for inherited fds. That's why interleaved writes to a shared log file don't overwrite each other when opened with O_APPEND. Each process has a limit on open fds (ulimit -n, often 1024 by default). A server holding 10,000 connections needs that raised, and "Too many open files" (EMFILE) usually means either a low limit or a leak.

The kernel's VFS (virtual file system) layer is an object-oriented interface (chapter 2's C vtables in practice) that every concrete filesystem implements: ext4, XFS, Btrfs, ZFS, NFS, FUSE, tmpfs, overlayfs.

Inodes

On Unix filesystems, a file's metadata lives in an inode (index node), not in the directory. An inode records:

  • Type (regular file, directory, symlink, device, socket, FIFO) and permission bits.
  • Owner UID and GID.
  • Size, link count, timestamps (atime, mtime, ctime; some filesystems also record birth time).
  • Where the data is: block pointers or extents (contiguous runs of blocks, as in ext4 and XFS).

What the inode doesn't contain is the file's name. Names live in directories. stat file shows the inode number and metadata, and ls -i lists inode numbers. A filesystem can run out of inodes before it runs out of space if it has millions of tiny files: df -i shows that.

Directories and paths

A directory is a special file that maps names → inode numbers. Resolving /home/asha/notes.txt means: start at the root inode, look up home in it, then look up asha in that directory, then look up notes.txt. Each step needs execute (x) permission on the directory. The kernel caches lookups in the dentry cache.

Directory operations are what make some filesystem operations atomic. rename(old, new) within one filesystem atomically replaces new. That gives the standard safe-write pattern for config files and any file that must never be seen half-written:

Text
1. write the full content to  config.json.tmp
2. fsync(config.json.tmp)            ← data is durable
3. rename(config.json.tmp, config.json)   ← atomic switch: readers see old or new, never partial
4. fsync(the directory)              ← the rename itself is durable

Permissions

Classic Unix permissions are three triplets of read, write and execute bits, for the owner, the group and others, shown as rwxr-x--- or in octal as 750 (chapter 6):

Bit On a file On a directory
r (4) Read contents List names
w (2) Modify contents Create, delete and rename entries (deleting a file needs w on the directory, not on the file)
x (1) Execute as a program Enter or traverse (cd, path lookup)

Special bits:

  • setuid (4xxx) on an executable runs it with the owner's privileges. passwd is setuid root so it can edit /etc/shadow. It's a classic privilege-escalation target.
  • setgid (2xxx): new files in a setgid directory inherit the directory's group.
  • sticky (1xxx) on a directory: only a file's owner can delete it. /tmp is 1777.

The umask removes bits from new files' default permissions (typically 022, so files get 644 and directories 755). Beyond the classic bits there are POSIX ACLs (setfacl), Linux capabilities (grant CAP_NET_BIND_SERVICE to bind port 80 without root), and mandatory access control (SELinux, AppArmor). Containers combine all of these with namespaces (Part VI). Running containers as non-root and with read-only root filesystems is standard hardening.

  • A hard link is just another directory entry pointing to the same inode. ln a b makes a and b indistinguishable names for one file. The inode's link count tracks the names, and the data is freed only when the count reaches 0 and no process has the file open. That's why deleting a 50 GB log file that a process still holds open doesn't free the space until the process closes it or restarts. lsof +L1 finds such files. Hard links can't cross filesystems or point to directories.
  • A symbolic (soft) link is a small file containing a path. It can cross filesystems and point to directories, and it can dangle if the target is removed. Symlinks are the basis of tricks like current → releases/2026-10-24 for atomic deploys (switch the symlink with an atomic rename), and also of security bugs: TOCTOU symlink attacks, and path traversal through symlinks in extracted archives.

Buffering, the page cache and fsync

Writing to a file doesn't write to the disk. The data goes through several layers of buffering:

app bufferBufWriter libc / stdFILE* buffer page cachedirty pages, RAM device cachevolatile? media flush()write() fsync(): durable
Every layer between write() and the platter or flash can hold your data. Only fsync (or equivalent) forces it through to stable storage.
  • The page cache holds file data in otherwise unused RAM. Reads served from it take nanoseconds, and that's why the "free" column in free -h looks small: Linux uses idle RAM as cache, shown under "buff/cache". Writes mark pages dirty, and background flusher threads write them out later (within about 30 seconds by default). write() returning success means "the kernel has it," not "it's on disk."
  • fsync(fd) blocks until the file's data and metadata reach stable storage, telling the device to flush its own volatile cache too. fdatasync skips non-essential metadata. They cost roughly 0.05–1 ms on NVMe SSDs with power-loss protection, and up to several ms on consumer drives and HDDs.
  • Durability means fsync. A database commit is durable only after the write-ahead log is fsynced (chapter 58). PostgreSQL's synchronous_commit, Kafka's flush.messages, and Redis's appendfsync always|everysec|no are all knobs on exactly this trade-off between durability and latency. Group commit batches many transactions' log records into one fsync.
  • fsync errors are serious. In 2018, PostgreSQL developers discovered ("fsyncgate") that on Linux, after a failed fsync, the dirty pages could be marked clean and a retried fsync would report success with data lost. PostgreSQL now panics and recovers from the WAL on fsync failure.
  • O_DIRECT bypasses the page cache. Databases with their own buffer pool use it so data isn't cached twice.

Journaling and crash consistency

Updating a file touches several on-disk structures: data blocks, the inode (size, block pointers), and the free-block bitmap. If power fails halfway, the filesystem can be left inconsistent: blocks marked used but unreferenced, or an inode pointing at garbage. Old filesystems needed a full fsck scan after a crash, which took hours on large disks.

A journaling filesystem (ext4, XFS, NTFS) first writes the intended changes to a journal (a log), commits it, then applies the changes in place. After a crash it replays committed journal entries and discards incomplete ones. Recovery takes seconds. It's the same write-ahead logging idea databases use, applied to filesystem metadata. ext4's default data=ordered mode journals metadata only, but writes data blocks before committing the metadata that points to them, so files don't end up pointing at stale blocks.

Copy-on-write filesystems (ZFS, Btrfs, APFS) never overwrite in place. They write new blocks, then atomically update pointers up the tree to a new root. Crash consistency comes for free, and so do cheap snapshots (keep the old root) and end-to-end checksums (a Merkle-like tree, chapter 3), which catch silent corruption. The costs are fragmentation and write amplification for random-update workloads such as databases.

Block storage

Underneath, storage devices expose an array of fixed-size blocks or sectors: 512 bytes or 4 KB logical, with 4 KB or larger physical units. The block layer queues requests, merges adjacent ones, and schedules them (mq-deadline, bfq, or none for NVMe).

HDD SATA SSD NVMe SSD
Random read latency 5–10 ms (seek + rotation) ~100 µs ~10–100 µs
Random IOPS ~100–200 ~50–100 K ~0.5–1.5 M+
Sequential throughput ~200 MB/s ~550 MB/s 3–14 GB/s
Queues 1 1 (NCQ: 32 deep) up to 64 K queues × 64 K deep

SSDs have quirks that software must respect. Flash can only be erased in large blocks (MBs) and written in pages, so the SSD's flash translation layer remaps writes and garbage-collects internally. Random small writes cause write amplification and wear. That's part of why LSM trees (sequential writes, chapter 3) suit SSDs. TRIM/discard tells the drive which blocks are free. Enterprise SSDs have power-loss protection capacitors, which make fsync cheap and safe. Consumer drives may not.

In the cloud, "disks" are usually network block storage (AWS EBS, GCP Persistent Disk, Azure Managed Disks) with provisioned IOPS and throughput limits and about 0.5–1 ms latency. Local NVMe instance storage is far faster, but it's lost when the instance stops. That trade-off shapes database deployments (Part VIII).

Input/output models

Blocking I/O

With blocking I/O, read(fd, buf, n) on a socket with no data yet puts the calling thread to sleep until data arrives. The model is simple: code reads top to bottom. To serve 10,000 concurrent clients, though, you need 10,000 threads, each mostly sleeping and each costing a kernel thread, a stack and context switches. This is the "C10K problem" (Dan Kegel, 1999).

Thread-per-connection with blocking I/O is perfectly good up to a few thousand connections: classic Tomcat, Spring MVC, PostgreSQL's process per connection. Virtual threads and goroutines make blocking code scale to hundreds of thousands of connections, because the runtime converts blocking calls into readiness waits underneath.

Non-blocking I/O

Set a descriptor to non-blocking mode (O_NONBLOCK), and read returns immediately with EAGAIN/EWOULDBLOCK when no data is ready. On its own that just means polling in a loop, which wastes CPU. Non-blocking I/O becomes useful when paired with a readiness notification mechanism that says which of thousands of descriptors are ready, so one thread can serve them all.

I/O multiplexing: select, poll and epoll

Mechanism How it works Cost per call Notes
select (1983) Pass bitsets of fds to watch; the kernel scans them all and returns which are ready O(n) every call; usually limited to fd < 1024 Portable, legacy
poll An array of struct pollfd instead of bitsets O(n) every call; no fd limit
epoll (Linux 2.6) Register interest once (epoll_ctl); epoll_wait returns only the ready fds O(ready) Linux's scalable answer
kqueue Like epoll, plus timers, signals and process events O(ready) BSDs, macOS
IOCP Completion-based (below) Windows

epoll has two modes. Level-triggered (the default) reports an fd as long as it remains readable. Edge-triggered (EPOLLET) reports only transitions to readable, so you must drain the socket until EAGAIN or you'll never hear about the leftover data.

This is the event loop architecture (the reactor pattern): one thread waits on epoll, dispatches ready events to handlers, and loops. Each handler must do a small amount of non-blocking work and return. That's how Nginx, Redis, Node.js (libuv), Netty, Vert.x and Spring WebFlux work. Go's netpoller and Tokio use the same epoll machinery underneath and present it as goroutines or async tasks.

C
// The skeleton of every epoll server (error handling trimmed)
int ep = epoll_create1(0);
struct epoll_event ev = { .events = EPOLLIN, .data.fd = listen_fd };
epoll_ctl(ep, EPOLL_CTL_ADD, listen_fd, &ev);

struct epoll_event ready[256];
for (;;) {
    int n = epoll_wait(ep, ready, 256, -1);           // sleep until something is ready
    for (int i = 0; i < n; i++) {
        int fd = ready[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 {
            char buf[4096];
            ssize_t r = read(fd, buf, sizeof buf);   // won't block: epoll said it's ready
            if (r <= 0) { close(fd); continue; }       // 0 = peer closed
            write(fd, buf, r);                         // echo (real code buffers partial writes)
        }
    }
}

Asynchronous I/O and io_uring

Readiness-based I/O (epoll) tells you when you can read without blocking, and then you still make the read system call. Completion-based asynchronous I/O works the other way: you submit "read into this buffer" and later get told it's done.

  • Windows IOCP has long been completion-based.
  • Linux AIO (io_submit) worked only for O_DIRECT files and was widely considered broken.
  • io_uring (Linux 5.1, 2019) uses two ring buffers shared between user space and the kernel (chapter 3): a submission queue and a completion queue. You write request entries into the SQ, the kernel posts results to the CQ, and with polling modes, high request rates need no system calls at all. It supports files, sockets, timeouts, accept, openat and more, with batching and linked operations.

io_uring gives the highest I/O throughput Linux has offered. TigerBeetle (written in Zig) is built on it, Tokio has tokio-uring, and Netty and some databases have io_uring transports. It has also been a large attack surface: Google disabled it on ChromeOS and in production servers after a run of kernel CVEs, and container runtimes' default seccomp profiles often block it.

Choosing an I/O model per language

Language Default model Scaling approach
C Blocking syscalls Write your own epoll/kqueue loop, or use libuv, libevent or liburing
C++ Blocking streams Boost.Asio (reactor/proactor), C++20 coroutines with Asio, std::execution (C++26)
Java Blocking (java.io, JDBC) Virtual threads (JDK 21+) with blocking code, or NIO selectors via Netty or WebFlux for event-loop style
Rust Blocking std::io async/await + Tokio (epoll/kqueue/IOCP; io_uring optional), or threads
Go Looks blocking: goroutines + netpoller The runtime does epoll for you; you just start goroutines
Zig Blocking std Moving to an Io interface whose implementation can be threaded, event-loop or io_uring based, chosen by the caller

The direction across the industry is clear. Write straightforward sequential code and let the runtime multiplex it, as Go, Java virtual threads, and Zig's new Io do, or use async/await where explicit control matters (Rust, C++). Callback-heavy reactive code (RxJava, Reactor) is now mostly reserved for genuine streaming and backpressure cases (roadmap chapter 48).

Lab: watching the operating system work

The kernel is invisible until you measure it. Each experiment below was run on this book's sandbox: a Linux 6.18 guest in a lightweight virtual machine (Firecracker-style), GCC 13, JDK 21. Virtualisation makes some operations slower than on bare metal (process creation and page faults especially), so read the numbers as orders of magnitude, and rerun them on your own machine.

What OS operations cost

C
syscall(SYS_getppid);                                    // a real system call: user → kernel → user
clock_gettime(CLOCK_MONOTONIC, &ts);                     // served by the vDSO: kernel data mapped into the process
pthread_create(&th, 0, noop, 0); pthread_join(th, 0);
pid_t p = fork(); if (!p) _exit(0); waitpid(p, 0, 0);
pid_t p = fork(); if (!p) execl("/bin/true", "true", (char *)0); waitpid(p, 0, 0);
write(a[1], &c, 1); read(b[0], &c, 1);                    // ping-pong with another process over two pipes
Text
raw syscall (getppid):              113 ns
clock_gettime via vDSO:              20 ns
thread create + join:             53075 ns
fork + exit + wait:              198698 ns
fork + exec(/bin/true) + wait:  1411795 ns
pipe round trip (2 context switches + 4 syscalls): 10798 ns

The ladder spans five orders of magnitude, and it explains several design choices you meet later:

  • A system call crosses into the kernel and back (~100 ns here; mitigations for speculative-execution attacks made this more expensive after 2018). Hot paths minimise syscalls (buffering, below; batching interfaces like io_uring, sendmmsg).
  • The vDSO (virtual dynamic shared object) lets clock_gettime read time from kernel-maintained memory without entering the kernel: 5× cheaper. That's why timestamps on every log line are affordable.
  • Thread creation costs tens of microseconds (kernel task, stack mapping, scheduler bookkeeping). Hence thread pools: create threads once, reuse them (chapter 11's project 4). Goroutines and Java virtual threads exist because even this is too expensive for one-per-request at high concurrency.
  • Process creation (fork) costs more (copying page tables), and exec of a new program much more (mapping a new binary, dynamic linking, chapter 10): ~1.4 ms here. A shell script that spawns a process per line of input is slow for this reason; servers that fork per request (old CGI) gave way to persistent processes and threads.
  • A context switch through pipes: about 5 µs per switch here (2–5 µs is typical on bare metal), including scheduler work and cache disruption. That's why synchronous hand-offs between threads in a hot loop are slow, and why event loops (one thread, many connections) scale.

Buffering: same bytes, 200× fewer system calls

Writing 100,000 lines with C's buffered fwrite versus a raw write() per line, counting system calls with strace -c:

C
if (argc > 1) write(fileno(f), line, len);   // one syscall per line
else fwrite(line, 1, len, f);                // stdio buffers 4 KB, then one write()
Text
mode 'buffered': 7 ms     → write() calls: 489
mode 'raw':      40 ms    → write() calls: 100000

The same 2 MB of output took 489 system calls with buffering and 100,000 without, and ran almost 6× faster. Every language's I/O library buffers for this reason (BufferedWriter in Java, bufio.Writer in Go, BufWriter in Rust, Python's default file objects), and forgetting to wrap a raw stream is a classic slowdown. The flip side: buffered data isn't written until it's flushed, which leads to the next experiment's surprise.

Virtual memory is lazy, and fork is copy-on-write

Map 512 MB, touch every page, then fork and let the child write half of it:

C
char *p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
for (size_t i = 0; i < len; i += 4096) p[i] = 1;            // first touch of each page
for (size_t i = 0; i < len; i += 4096) p[i] = 2;            // second touch
fflush(stdout);                                             // or the child inherits (and re-prints) unflushed output
pid_t c = fork();
if (c == 0) { for (size_t i = 0; i < len / 2; i += 4096) p[i] = 3; ... }   // child writes half
Text
after mmap(512 MB):     RSS    +120 KB, minor faults     +10
after touching pages:   RSS +524540 KB, minor faults +131086  (1928 ns per fault)
touching them again:    16 ns per page (no faults: already mapped)
child wrote 256 MB:     minor faults  +65538  (copy-on-write, 3467 ns per page)
parent still sees:      p[0] = 2 (its own copy untouched)
after mmap addresses only after first touch fault → frame allocated after fork + child write parent child shared shared copy written page copied RSS grows only as pages are touched; fork costs page tables, not memory
Lazy allocation and copy-on-write. mmap only reserves virtual addresses; the first write to each page causes a minor page fault in which the kernel allocates a zeroed physical frame. After fork, parent and child page tables point at the same frames marked read-only; a write by either causes a fault in which the kernel copies just that page.
  • mmap of 512 MB increased resident memory by only 120 KB: it reserved virtual addresses, nothing more.
  • Touching each 4 KB page caused 131,086 minor page faults (one per page): the kernel allocates and zeroes a physical frame on first access, about 2 µs each here. Afterwards, accesses cost nanoseconds. This laziness is why a process's virtual size (VSZ) can be enormous while its resident size (RSS) is small, and why memory "allocated" by malloc may not exist yet (Linux overcommits; the OOM killer acts when touched memory exceeds what's available).
  • After fork, the child shares all the parent's frames; its 256 MB of writes caused 65,538 copy-on-write faults, each copying one page. The parent's data is untouched. This is how fork is affordable for big processes, how Redis takes snapshots (fork, then the child writes the dataset while the parent keeps serving; memory grows only by the pages the parent modifies meanwhile), and why huge-page-backed processes can see expensive forks.

The fflush(stdout) line has a story. Without it, the first run of this program printed its first three lines twice: when stdout is a pipe, stdio buffers output; fork copies the buffer into the child; both processes eventually flush it. Flush (or use unbuffered output) before fork, and use _exit rather than exit in a child that shouldn't flush the parent's buffers.

A deadlock, detected

Two threads transfer money between two accounts, locking them in opposite orders:

Java
static void transfer(Object from, Object to, String name) {
    synchronized (from) { sleep(100); synchronized (to) { System.out.println(name + " done"); } }
}
// thread 1: transfer(accountA, accountB)    thread 2: transfer(accountB, accountA)
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
for (ThreadInfo ti : mx.getThreadInfo(mx.findDeadlockedThreads()))
    System.out.println(ti.getThreadName() + " is " + ti.getThreadState() + " waiting for lock held by " + ti.getLockOwnerName());
Text
transfer-A-to-B is BLOCKED waiting for lock held by transfer-B-to-A
transfer-B-to-A is BLOCKED waiting for lock held by transfer-A-to-B

All four Coffman conditions hold (mutual exclusion, hold and wait, no preemption, circular wait), so neither thread will ever finish, and nothing crashes: the symptom in production is requests that never complete and a thread pool that slowly fills. The JVM can find cycles in its monitor graph (jstack <pid> prints "Found one Java-level deadlock"; findDeadlockedThreads gives the same programmatically), as can database engines for row locks (PostgreSQL aborts one transaction with "deadlock detected"). The fix breaks circular wait: lock in a global order (here: always the account with the lower id first), or use tryLock with a timeout and back off, or avoid holding two locks at once (chapter 8's lock-ordering discipline, Volume 17's L5 rules).

Revision sheet: operating systems

Key ideas

  • The OS shares hardware, isolates programs and provides abstractions (processes, threads, files, sockets, virtual memory).
  • Kernel mode vs user mode, enforced by the CPU; programs enter the kernel by system calls, faults and interrupts.
  • A process has an address space, file descriptor table, credentials and at least one thread; Unix creates processes with fork + exec and reaps them with wait (an unreaped child is a zombie).
  • The scheduler time-slices ready threads across cores (Linux: CFS, and from 6.6 EEVDF); states: running, ready, blocked, exited. Context switches cost microseconds plus cache disruption.
  • Threads share memory; races occur when unsynchronised accesses include a write. Tools: mutexes, read-write locks, condition variables, semaphores, atomics, message passing. Deadlock needs mutual exclusion, hold-and-wait, no preemption and circular wait; break any one.
  • Virtual memory: per-process page tables, 4 KB pages, demand paging, copy-on-write after fork, page faults, swapping, memory-mapped files.
  • Filesystems: inodes hold metadata; directories map names to inodes; hard vs symbolic links; journaling for crash consistency; fsync for durability.
  • I/O models: blocking, non-blocking, multiplexed (select/poll/epoll, kqueue), asynchronous (io_uring); the basis of event loops, Go's netpoller and Java virtual threads.
  • Permissions: user/group/other rwx bits, root, capabilities; checks happen inside system calls.

Numbers to remember

  • System call overhead: roughly 50–500 ns depending on the call and mitigations; context switch: about 1–5 µs.
  • Linux default time slice granularity: a few milliseconds.
  • File descriptors 0, 1, 2 = stdin, stdout, stderr; default soft limit often 1,024 open files (ulimit -n).
  • Permission octal: r = 4, w = 2, x = 1 (644 files, 755 directories and executables, 600 secrets).

Pitfalls

  • Reading or writing one byte per system call; buffer instead.
  • Assuming write returned means data is on disk (it's in the page cache until fsync).
  • Forgetting to close descriptors or reap children; leaking threads.
  • Holding a lock while doing I/O or calling unknown code.
  • Taking locks in inconsistent orders (deadlock).
  • Treating kill -9 as a normal shutdown: no cleanup, no flush.

Glossary

  • PID / PPID: process ID / parent's process ID.
  • File descriptor: a small integer naming an open file, pipe or socket in a process.
  • Page fault: an access to a page not currently mapped; the kernel loads or allocates it (or kills the process).
  • Copy-on-write: sharing pages until one side writes, then copying.
  • Signal: an asynchronous notification to a process (SIGINT, SIGTERM, SIGKILL).
  • Critical section: code that must not run in more than one thread at a time.