An illustrated, practical foundation with safe local experiments and complete answers
A substantial original guide to processes, scheduling, virtual memory, concurrency, files, crash behavior, I/O, isolation, and resource-aware programs.
14 chapters14 diagrams28 practice tasks
Clear explanations. Worked examples. Practice with reasoning. Original text · CC BY-SA 4.0 Code · MIT
Before you begin
How to use this guide
Developers and students who can read small programs and want to reason clearly about the machine beneath them.
Helpful background
Run Python 3 scripts and navigate a terminal
Read small functions, loops, and exceptions
Basic arithmetic; address calculations are worked step by step
What you will be able to do
Explain process and thread lifecycles and their ownership responsibilities
Calculate teaching schedules and virtual-address translations
Find invariants, race conditions, circular waits, and correct waiting predicates
Distinguish file handles, buffered writes, atomic publication, and durability
Build a bounded local worker experiment and interpret its performance honestly
A useful study rhythm
Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.
For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.
Scope and assumptions
Most executable examples use Python 3.11+ standard-library APIs and temporary local files. Linux-specific semantics are labeled; macOS and Windows can differ.
Classic scheduling and paging examples are explicitly simplified teaching models, not claims about the exact policy of every current production kernel.
CPython 3.11 threading notes concern that interpreter configuration; they are not universal statements about all Python versions or all OS threads.
This guide teaches durable foundations and safe local experiments, not complete kernel implementation, hostile-code sandboxing, production storage protocols, or every real-time scheduling rule.
External books and MIT lecture videos remain linked at their authorized hosts. Original explanations and diagrams here are not copied textbook chapters.
Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.
Chapter 01
Meet the operating system without memorizing a list
Explain why applications need protected access to shared hardware.
By the end of this chapter
Separate a program, process, kernel, and system call
Recognize abstraction, isolation, and resource-sharing tradeoffs
The problem an operating system solves
Several applications want the same finite machine at once. A music player needs timely audio, a browser needs memory and network access, and a file copy needs storage bandwidth. Letting each application control every device and every memory location directly would make accidental interference routine. An operating system coordinates access, supplies useful abstractions, and enforces boundaries. Its decisions affect correctness as well as performance: a fast program is not useful if it can silently overwrite another program’s memory.
The kernel is the privileged core responsible for mechanisms such as managing address spaces, scheduling execution, and handling device interactions. User-space programs run with more restricted access and ask for protected operations through system calls. A library function is not necessarily a system call: it may calculate entirely in user space, buffer several operations, or invoke multiple kernel services. When a program writes text, layers of language runtime, library buffering, kernel interfaces, and device handling can be involved.
A protected request for a resource. An application calls a library, the library may invoke a system call, and the kernel checks and performs privileged resource work before returning a result.Scroll horizontally to read the full diagram on a small screen.
positive pid: True
platform: Darwin, Linux, or Windows, depending on the host
A process identifier is a handle used to refer to a process in a particular context, not a permanent identity for the application’s whole lifetime across restarts. A filename similarly names an object through a namespace; it is not the physical storage location. Abstractions simplify work by hiding details, but troubleshooting sometimes requires you to look beneath them. Ask which layer owns the observed state, which guarantees are documented, and which details vary across systems.
This guide uses Unix-like terminology and portable Python for most experiments. Linux-specific tools and kernel mechanisms are labeled. macOS has many related interfaces but is not Linux, while Windows has different native process and I/O models. The small scheduling and memory simulators are teaching models; they do not claim to reproduce every policy of a current production kernel. That separation lets you learn durable ideas without mistaking one diagram for every real machine.
Treat process lifecycle as a resource protocol rather than just starting a command.
By the end of this chapter
Distinguish fork, exec, exit, and wait
Launch a child safely and inspect its outcome
A program becomes a running process
A program is stored instructions and data in a form that can be loaded. A process is an executing instance with state: an address space, execution context, open resources, and identity information. Two processes can run the same program while keeping distinct private state. Conversely, a process can replace the program it runs. On Unix-like systems, fork and exec illustrate that separation: fork creates a child process, while an exec-family operation replaces the calling process’s program image.
After fork, parent and child continue from the fork result but receive different return values. Their private address spaces are logically separate, often implemented efficiently with copy-on-write until a write requires distinct pages. Some resources, such as references to open file descriptions, have sharing relationships that matter. Forking a multithreaded program has extra hazards because only the calling thread continues in the child while inherited lock state may reflect vanished threads. Prefer a documented high-level process API for ordinary tasks.
The Unix-like process lifecycle. A parent starts a child, the child can replace its program, execution ends with an exit status, and the parent collects the result.Scroll horizontally to read the full diagram on a small screen.
Passing an argument list with shell=False avoids interpreting ordinary data as shell syntax. It does not make an unsafe invoked program safe; you must still choose the executable and arguments appropriately. Capture only bounded output in real services, because a child can produce more output than memory can hold. Use a timeout when the caller cannot wait indefinitely, and understand the API’s process-tree and platform-specific cancellation behavior.
When a child terminates, the parent should collect its status through wait or a higher-level equivalent. A Unix zombie retains a small termination record until it is reaped; it is not a running worker consuming CPU. An orphan is a different relationship involving the loss of the original parent. Do not treat every process-state label as a reason to send an uncatchable signal. First establish who owns the process and what cleanup contract should apply.
Explain concurrency without assuming simultaneous execution.
By the end of this chapter
Compare process isolation with thread sharing
Trace ready, running, and blocked states
One process can contain several execution paths
A thread is an execution context within a process. Threads commonly share the process’s address space and many resources while keeping their own stacks and register state. Sharing makes communication convenient but also creates opportunities for one thread to observe another’s unfinished update. Separate processes usually begin with stronger private-memory boundaries, although explicit shared memory and communication channels can cross them. The correct choice depends on failure containment, communication cost, and the work being performed.
Concurrency means multiple activities can make progress over overlapping periods. Parallelism means work actually executes at the same time on distinct execution resources. A single CPU core can interleave several runnable threads without executing all of them simultaneously. A thread can also block while waiting for I/O or synchronization. At that point another runnable thread can use CPU time. The distinction explains why concurrency can help an I/O-heavy application even when CPU parallel speedup is limited.
State
Meaning in a simplified model
Typical next event
Ready
Able to run but waiting for CPU time
Scheduler dispatches it
Running
Currently executing
Preemption, block, or completion
Blocked
Waiting for an event or condition
I/O or synchronization makes it ready
The state transitions matter more than a slogan. A runnable thread can be dispatched, block on an event, become ready again, and later finish; blocked time is different from CPU execution.Scroll horizontally to read the full diagram on a small screen.
A context switch saves enough execution state to resume one activity later and restores another’s state. The cost includes direct bookkeeping and possible indirect effects on caches and translation information. A switch is not inherently a mistake: without switching, one waiting or long-running activity could make the machine unresponsive. The engineering question is whether the amount of concurrency helps the workload enough to justify coordination and scheduling costs.
Join a bounded pair of threads python
from threading import Thread
from queue import Queue
results = Queue()
def work(value):
results.put(value * value)
threads = [Thread(target=work, args=(x,)) for x in (2, 3)]
for thread in threads: thread.start()
for thread in threads: thread.join(timeout=2)
assert all(not thread.is_alive() for thread in threads)
print(sorted(results.get() for _ in threads))
Expected result
[4, 9]
The sorted result avoids claiming a fixed completion order. The queue supplies a documented coordination mechanism rather than relying on incidental timing. For standard CPython 3.11 builds, the interpreter lock limits simultaneous execution of Python bytecode by threads; I/O can still overlap. This is a runtime-specific property, not the definition of an operating-system thread, and newer interpreter configurations can differ. Measure the actual runtime and workload before promising a speedup.
Calculate scheduling tradeoffs with small timelines
Use response time, turnaround, and waiting time to compare policies.
By the end of this chapter
Calculate basic scheduling metrics
Explain why teaching policies are not current-kernel specifications
Choose a metric before choosing a policy
A scheduler chooses which runnable work receives CPU time. Different goals compete: interactive response, throughput, fairness, predictable latency, and efficient use of hardware. Response time measures delay until a task first gets service. Turnaround measures completion time minus arrival time. Waiting time counts time ready but not running in a simplified CPU-only model. These are different metrics, so one policy can improve one while harming another.
For a first experiment, assume one CPU, all tasks arrive at time zero, no I/O, and negligible switching overhead. First-come-first-served runs tasks in arrival order to completion. If A needs 8 units, B needs 2, and C needs 1, completion times are 8, 10, and 11. Mean turnaround is 29/3, about 9.67. The assumptions are deliberately simple so every number can be checked. They do not describe a complete desktop workload.
Compute a first-come-first-served timeline python
tasks = [("A", 8), ("B", 2), ("C", 1)]
time = 0
turnaround = []
for name, burst in tasks:
start = time
time += burst
turnaround.append(time)
print(name, start, time)
print(round(sum(turnaround) / len(turnaround), 2))
Shortest-job-first would run C, then B, then A in that simplified example, lowering mean turnaround to (1+3+11)/3 = 5. It assumes useful knowledge about future service time, and a stream of short work can harm long work under naive policies. Round-robin gives each ready task a bounded time slice before rotating it to the queue’s end. A short slice can improve initial response, but very frequent switches add overhead. A large slice begins to resemble running each task for a long uninterrupted period.
A round-robin teaching model. Runnable jobs wait in a queue. The scheduler selects the front job, runs up to one quantum, and requeues unfinished work. Real schedulers consider more state.Scroll horizontally to read the full diagram on a small screen.
Real operating systems account for priority, multiple cores, affinity, blocking, wakeups, and policy-specific behavior. Linux scheduling implementation has evolved, so do not learn an unqualified claim that one named algorithm describes all current Linux tasks. The Linux scheduling API reference is useful for policies and interfaces, while kernel documentation explains a particular implementation. Use simulation to understand tradeoffs, then use the host’s tools to observe its actual behavior.
Separate the addresses a program uses from the physical memory backing them.
By the end of this chapter
Explain mappings, permissions, stack, heap, and shared regions
Distinguish virtual size, residency, and allocation
Each process sees its own address space
An address space is the set of addresses and mappings a process can use under its protection rules. A virtual address is translated through hardware-supported mechanisms and operating-system-maintained information to a physical location or another result such as a fault. Two processes can use the same numeric virtual address and reach different physical memory. The abstraction helps isolation, relocation, and controlled sharing; it is not merely a trick for pretending that a disk is RAM.
A process typically has code mappings, global data, dynamically allocated regions often called the heap, thread stacks, shared libraries, and mapped files. The exact arrangement depends on the system, executable format, runtime, and security features. A diagram with one growing heap and one descending stack is a useful simplified model but not a universal layout contract. Address randomization and multiple mapped regions make real maps more complex.
A simplified process address space. Code, data, dynamic allocations, mappings, and stacks are distinct regions with permissions. Their order and size are illustrative, not fixed across operating systems.Scroll horizontally to read the full diagram on a small screen.
The example shows two Python-level views of the same mutable buffer, not raw physical memory. The runtime’s object allocator, virtual-memory mappings, and physical-page residency are different layers. A request to reserve address space need not mean every page immediately has physical backing. Touching a page can trigger additional work. Conversely, freeing a language object does not require the runtime to return every byte to the operating system at once.
When investigating memory, ask what is measured. Virtual size includes address-space reservations and mappings. Resident set measurements concern pages currently in physical memory under the tool’s accounting rules. Shared pages and caches complicate sums across processes. A high number is not automatically a leak; a leak means resources remain unintentionally retained or unusable as the program continues. Compare trends under a repeatable workload and inspect references or allocations before making a diagnosis.
Do a complete translation calculation before learning implementation variants.
By the end of this chapter
Split a virtual address into page number and offset
Distinguish a TLB miss from a page fault
Fixed-size pages simplify placement
Paging divides virtual memory into pages and physical memory into page frames. A page table records mappings and relevant state such as permissions or presence. With a 4,096-byte page in a teaching example, the low 12 address bits represent the offset within a page. The remaining bits identify the virtual page. Page size varies by architecture and mapping; 4 KiB is an example, not a promise about every machine or every page in one process.
To translate virtual address 0x2345 with 4-KiB pages, split it into virtual page 0x2 and offset 0x345. If the table maps virtual page 2 to physical frame 9, the physical address is frame base 0x9000 plus 0x345, giving 0x9345. The offset is preserved because translation chooses the frame containing the page’s corresponding bytes. Permissions are checked as part of the access rules, not ignored after finding a frame number.
Translate, then access. Split the address, look up the mapping and permissions, combine a physical frame with the unchanged offset, then access memory if allowed.Scroll horizontally to read the full diagram on a small screen.
A translation lookaside buffer, TLB, caches address-translation information so ordinary accesses do not require a full page-table walk every time. A TLB miss means the cached translation was not found. The processor can often walk the tables and fill the TLB without an operating-system page-fault handler. A page fault is a different event requiring the system to handle a missing or disallowed access condition. Conflating the two makes both performance analysis and debugging confusing.
Not every page fault means data is read from a swap device. Demand-zero allocation, copy-on-write, and already-cached file pages can produce faults with different work involved. A protection violation may be invalid rather than recoverable. The kernel can create a mapping, wait for I/O, or report a fault to the process depending on the access and policy. Observe minor versus major fault terminology using the specific operating system’s definitions.
Worked example · Estimate translation overhead under explicit assumptions
Assume a hypothetical 100-ns memory access, a 1-ns TLB check, and a single-level page table whose miss adds one 100-ns memory access.
At a 99% TLB hit rate, the model gives 1 + 100 + 0.01×100 = 102 ns average.
Real processors can overlap work and have multilevel caches/tables. The calculation teaches weighted costs; it is not a hardware benchmark.
Result: A rare expensive path can matter, and a simple model must state what it omits.
Use locality to reason about caches and memory pressure
Learn replacement policies with a trace you can inspect.
By the end of this chapter
Explain temporal and spatial locality
Simulate LRU and reason about working sets
Programs revisit nearby and recent data
Temporal locality means recently used data is likely to be used again. Spatial locality means nearby data is likely to be accessed soon. These patterns make caches useful at several levels, from CPU caches to file caches. A sequential scan, a repeated small lookup table, and random access across a huge dataset have different locality. An optimization that helps one pattern can hurt another. Describe the access trace before claiming that a bigger cache or a different container is automatically faster.
The working set is the data actively needed over a meaningful interval. When active demand fits the available fast storage, reuse can be effective. When it greatly exceeds available physical memory, the system may spend substantial effort reclaiming and faulting pages instead of doing useful work. This can produce thrashing-like behavior. A single page-fault count is not enough to diagnose it; look at fault rates, I/O, memory pressure, and useful throughput together.
A locality feedback loop. The workload touches a set of pages, resident capacity determines reuse, misses trigger work, and the resulting stalls affect useful progress.Scroll horizontally to read the full diagram on a small screen.
from collections import OrderedDict
frames = OrderedDict()
faults = 0
for page in [1, 2, 1, 3, 1, 2]:
if page not in frames:
faults += 1
if len(frames) == 2:
frames.popitem(last=False)
else:
del frames[page]
frames[page] = None
print(faults)
print(list(frames))
Expected result
4
[1, 2]
The oldest dictionary entry represents the least recently used page. Reusing a page moves it to the recent end. On the trace, pages 1 and 2 first fault, the second access to 1 hits, page 3 evicts 2, the next 1 hits, and the final 2 faults. The four faults are a result of this exact capacity and trace. A real operating system cannot usually maintain perfect per-access LRU bookkeeping for all memory cheaply, so it uses implementation-specific approximations and other information.
Separate policy from mechanism. A mechanism can track access indicators, maintain lists, or move pages; a policy decides what to prefer under pressure. Replacement interacts with dirty pages, file-backed data, sharing, priorities, and reclaim costs. A clean page that can be reread may have a different eviction cost from a modified page requiring writeback. A good explanation says which resources and costs its simple model ignores.
Find the operation that must remain indivisible from another thread’s point of view.
By the end of this chapter
Trace a lost update
Use locks for compound state changes and keep critical sections purposeful
A race is about allowed interleavings
Suppose two workers each add one to a shared counter. At a conceptual machine level, "add one" may involve reading the current value, calculating a new value, and writing it back. Both workers can read zero before either writes, then both write one. The intended result is two, but one update disappears. A race condition means the result depends incorrectly on timing or ordering. In languages with a formal memory model, unsynchronized conflicting memory accesses can have even stronger consequences than this simple lost-update story.
An invariant is a condition that should remain true at the boundaries visible to the rest of the program. For an account transfer, the sum of two balances may need to stay constant while neither balance becomes invalid. Protecting only one assignment can leave other threads observing half a transfer. Identify the whole state transition and its readers before choosing where to lock. A lock is a mechanism for coordination; it does not automatically identify the correct invariant for you.
How a lost update happens. Both workers read the same old value, calculate independently, and overwrite the shared counter with the same new value.Scroll horizontally to read the full diagram on a small screen.Force the conceptual lost-update trace python
from threading import Lock, Thread
lock = Lock()
counter = 0
def add_many():
global counter
for _ in range(1000):
with lock:
counter += 1
threads = [Thread(target=add_many) for _ in range(2)]
for thread in threads: thread.start()
for thread in threads: thread.join()
print(counter)
Expected result
2000
Every participant that accesses the protected state must follow the same synchronization discipline. One carefully locked writer cannot make an unsynchronized reader correct by magic. Keep critical sections small enough to avoid unnecessary blocking but large enough to preserve the invariant. Avoid performing slow network requests while holding a shared-state lock unless the design explicitly requires that coupling. A lock held across unpredictable I/O can turn one slow dependency into a queue for unrelated work.
Often the clearest fix is to reduce sharing: give each worker private results, then combine them in one place; pass messages through a queue; or use an immutable representation. These choices can make ownership easier to reason about. They still have costs and ordering questions, but the protected state becomes smaller. Do not rely on a particular CPython version’s convenient behavior as a universal proof that a compound algorithm is thread-safe.
Use condition variables and bounded queues to coordinate useful work.
By the end of this chapter
Explain predicate-based waiting
Build a producer-consumer workflow with explicit termination
Sleeping and polling solve different problems
A worker may need to wait until data exists, space is available, or another task has finished. Repeatedly checking a flag in a tight loop can waste CPU time and create contention. Adding arbitrary sleeps can reduce CPU use but introduces delays and still fails to establish a correctness relationship. Proper waiting coordinates the state predicate and the wakeup mechanism so a worker does not miss the transition it needed to observe.
A condition variable is used with a lock protecting shared state. The worker checks a predicate while holding that lock, waits in a loop when the predicate is false, and rechecks after waking. Waiting releases the associated lock while the thread sleeps and reacquires it before returning. The loop matters because waking is a reason to recheck, not a promise that the desired state is still true. Another worker may have consumed the item first, and some APIs permit spurious wakeups.
Wait on a predicate, not on hope. Acquire the lock, inspect shared state, wait while the predicate is false, then perform the state transition while still following the lock discipline.Scroll horizontally to read the full diagram on a small screen.
A bounded queue supplies a useful ownership boundary
A producer and a worker with explicit completion python
from queue import Queue
from threading import Thread
work = Queue(maxsize=2)
results = []
def consume():
while True:
item = work.get()
try:
if item is None:
return
results.append(item * 2)
finally:
work.task_done()
worker = Thread(target=consume)
worker.start()
for item in (1, 2, 3):
work.put(item)
work.put(None)
work.join()
worker.join()
print(results)
Expected result
[2, 4, 6]
The queue’s capacity applies backpressure: the producer waits when it has filled the allowed pending slots. That bounds one part of the system’s memory demand. The sentinel value None is a protocol choice meaning shutdown, so None cannot also be an ordinary item in this example. With several consumers, send an appropriate termination signal to each or use another documented shutdown design. Every successful get must be paired with task_done, including the sentinel, or join can wait forever.
The example uses one consumer, so result order follows the queued order. With multiple workers, completion order can differ even when dequeue order is FIFO. If results must be returned in input order, attach sequence numbers and reorder deliberately or use a suitable abstraction. Failure handling also needs design: an exception should not leave the queue’s bookkeeping inconsistent or silently lose a task that the application promises to process.
Recognize deadlock, starvation, and unsafe lock ordering
Understand liveness failures separately from wrong numeric answers.
By the end of this chapter
Trace a circular wait
Choose an ordering or ownership design that breaks the cycle
A program can be wrong by never finishing
Deadlock occurs when activities wait for one another in a way that prevents the required progress. The classic two-lock example is small: worker A holds lock X and waits for Y, while worker B holds Y and waits for X. Each worker follows a locally understandable instruction, yet the combined state cannot advance. Correctness therefore includes liveness questions as well as the safety question of whether a completed result has the right value.
Four conditions are often used to analyze resource deadlock: mutual exclusion, holding resources while waiting for others, no forced preemption of those resources, and circular wait. They are a reasoning framework for the specified resource model, not a magical diagnostic command. Breaking a suitable condition can prevent the modeled deadlock, but the remedy has costs. For example, taking every lock at once can serialize too much work, and forcibly interrupting an operation can leave application state inconsistent.
The circular-wait trap. A owns X and requests Y while B owns Y and requests X; neither releases what the other needs.Scroll horizontally to read the full diagram on a small screen.Encode a consistent acquisition order python
from contextlib import ExitStack
from threading import Lock
locks = {"account-a": Lock(), "account-b": Lock()}
keys = ["account-b", "account-a"]
with ExitStack() as stack:
for key in sorted(set(keys)):
stack.enter_context(locks[key])
print("both locks acquired in canonical order")
A global lock order can remove cycles when every relevant participant follows the same rule. Use stable resource identifiers and handle the case where two logical names refer to the same lock; acquiring a non-reentrant lock twice can deadlock one thread against itself. The example removes duplicate keys before ordering. In a real design, consider whether a single owner or message-passing boundary would make the invariant simpler than coordinating several locks.
Starvation differs from deadlock: a system can keep doing useful work while one task never receives enough access to finish. Livelock differs again: tasks actively react to one another but fail to make useful progress, such as repeatedly abandoning and retrying at the same time. Fairness policies, bounded retries, randomized backoff, and reduced contention address different aspects. Name the observed failure rather than calling every wait a deadlock.
Lock-acquisition timeouts can help detect or escape a wait, but the caller must know how to leave state consistent. An expired timeout does not automatically roll back arbitrary earlier writes. If a transfer partly changed state before waiting for another resource, simply returning an error may be incorrect. Acquire the needed protection before the mutation when possible, keep transitions atomic at the right boundary, and design recovery explicitly.
Understand files, names, descriptors, and permissions
Follow the handle your program uses instead of treating a path as the file itself.
By the end of this chapter
Distinguish pathname, descriptor, and open-file state
Explain close, offsets, and permission boundaries
A path names an object through a namespace
A pathname is interpreted through directories and the process’s filesystem context. A file descriptor is a small process-local integer referring to an open resource under Unix-like interfaces. The descriptor is not the filename or the disk block address. After opening a file, operations use the handle and associated open-file state. Renaming a path and changing an already open handle are therefore not the same event. This distinction explains many log-rotation and temporary-file surprises.
An open-file description can hold state such as the current offset and access mode. Duplicated descriptors can share that underlying offset, so reading through one descriptor can affect where another shared reference reads next. Distinct opens may have independent offset state even for the same file. Avoid building a correctness argument around the numeric descriptor value itself: a closed number can be reused later for a different resource.
Two opens have separate positions python
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "notes.txt"
path.write_text("ABCDE", encoding="ascii")
with path.open("r", encoding="ascii") as first, \
path.open("r", encoding="ascii") as second:
print(first.read(2))
print(second.read(1))
print(first.read(1))
Expected result
AB
A
C
A path lookup produces a usable handle. The process resolves a name and checks access to obtain a descriptor, which refers to open-file state and the underlying file object.Scroll horizontally to read the full diagram on a small screen.
A context manager closes a Python file on normal exit and exceptions. Closing releases that handle; it does not mean all possible references to the underlying file disappeared or that every data update is durable on storage. Resource leaks occur when handles accumulate beyond the application’s intended lifetime. A service that leaks one descriptor per request can fail long before it runs out of memory, even when each request’s text processing is correct.
Unix-style permission bits distinguish read, write, and execute/search capabilities for owner, group, and others, with additional mechanisms such as ACLs and platform policies possible. Directory search permission is important for reaching a named entry; a file’s mode alone does not describe every path-access condition. Check the actual API error and context. A permission failure should not be "fixed" by broadly opening every file to all users.
Term
What it describes
Common mistake
Pathname
A route through a namespace
Treating it as a permanent object identity
Descriptor
A process-local open reference
Assuming its integer is globally unique
Close
Release this open reference
Assuming it guarantees storage durability
For temporary work, create a dedicated temporary directory with a managed lifetime, write only the exercise’s own files, and let the context remove them. Keep output paths separate from secrets and source configuration. If a program needs atomic publication or crash durability, use the next chapter’s stronger concepts rather than assuming that a successful write call solves every persistence problem.
Reason about writes, atomic replacement, and crashes
Define what survives before using the word "saved".
By the end of this chapter
Distinguish buffered writes from durability
Explain a carefully scoped temporary-file replacement pattern
There are several meanings of "written"
A language-level write may copy bytes into a runtime buffer. Flushing that buffer passes work toward the operating system, but the kernel and storage hardware can still have pending work. A successful system write can report acceptance of bytes without proving survival of a sudden crash. Durability is a stronger property with documented synchronization requirements and hardware assumptions. If an application tells a learner that progress is saved permanently, it should know which boundary has actually acknowledged the state.
Filesystems organize persistent names, metadata, and data blocks. Updating a file can require multiple lower-level changes. A crash between those changes is why journaling, copy-on-write designs, ordering constraints, and recovery procedures exist. These mechanisms have different guarantees. Do not infer that the presence of a journal makes every recent user-data write durable. A filesystem’s consistency after recovery and an application’s latest committed state are related but different questions.
Persistence has several acknowledgment boundaries. Data moves through a user buffer, kernel cache, storage path, and durable medium; a successful earlier boundary does not automatically imply the later ones.Scroll horizontally to read the full diagram on a small screen.
Publish a complete file instead of exposing half a rewrite
A local atomic-replacement teaching pattern python
import json
import os
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
target = Path(directory) / "progress.json"
temporary = Path(directory) / "progress.tmp"
with temporary.open("w", encoding="utf-8") as stream:
json.dump({"lessons": 3}, stream)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, target)
print(json.loads(target.read_text(encoding="utf-8")))
Expected result
{'lessons': 3}
Writing a temporary file in the same directory and then replacing the target can let concurrent readers see a complete old or complete new name binding rather than a partially rewritten target, under the platform’s documented replacement semantics. The example is not a universal crash-durability guarantee. On relevant Unix/Linux filesystems, persisting the containing directory can be necessary for the renamed entry to survive a crash; filesystem, mount, storage, and platform behavior must be checked. Cross-filesystem replacement is a different case.
A robust application also handles synchronization errors, permissions, storage exhaustion, interrupted work, and temporary-file cleanup. It must define whether an error means the old version is certainly retained, the new version is published, or the outcome needs reconciliation. Backups and checksums can detect or recover from additional failures, but they also need a tested restore path. For a real multi-record transactional workload, an appropriate database is often safer than inventing a storage protocol from this introductory example.
Connect I/O, event loops, containers, and resource limits
See which mechanism changes the view of resources and which controls consumption.
By the end of this chapter
Distinguish blocking I/O, readiness, and asynchronous completion
Separate namespaces, limits, virtual machines, and security claims
Waiting can be organized in several ways
A blocking I/O call can put the calling thread to sleep until progress or an error is available. Nonblocking I/O returns promptly when the operation cannot currently proceed. Readiness interfaces let an application monitor several handles and learn which may support I/O now. Completion-based interfaces report that submitted work completed. These are related tools, not synonyms. A readiness event does not mean an entire application message is present or that any amount of requested I/O will finish without further waiting.
An event loop coordinates many state machines on a small number of threads. Each operation must make bounded progress and yield control rather than performing an unrelated long blocking call in the loop. Otherwise one slow action stalls all the work sharing that loop. Linux epoll, BSD/macOS kqueue, and Windows completion facilities differ in API and semantics. A portable library can select an appropriate backend, but your application still needs correct framing, cancellation, and resource limits.
Ask which readiness selector the host chooses python
import selectors
with selectors.DefaultSelector() as selector:
print(type(selector).__name__)
Expected result
Typical: KqueueSelector on macOS or EpollSelector on Linux; platform and build may differ.
An event loop is coordination, not magic parallelism. The loop waits for relevant events, runs a bounded callback, updates state, and returns to waiting while other work remains eligible.Scroll horizontally to read the full diagram on a small screen.
A different resource view is not unlimited isolation
A virtual machine presents virtualized hardware to a guest operating system. A container commonly packages processes using host-kernel isolation mechanisms and resource controls. Linux namespaces can give a process a different view of resources such as process IDs, mounts, or networking. Control groups can account for and limit resource use. Neither mechanism alone establishes every security property. Containers share important host-kernel machinery, and configuration, privileges, mounts, and kernel vulnerabilities affect the actual boundary.
Resource limits improve predictability only when aligned with the workload. A memory cap can turn excessive allocation into a process failure rather than a host-wide shortage, but the application must recover or report failure appropriately. CPU quotas can create throttling that looks like unexplained latency. Descriptor limits can stop new connections. Observe the resource that is constrained instead of assuming that a host with idle-looking CPU must give every container unrestricted execution.
Mechanism
Main teaching purpose
Does not imply
Namespace
A scoped view of a resource
A complete independent kernel
Control group
Resource accounting and control
Correct application authorization
Virtual machine
A guest OS on virtualized hardware
Immunity to every shared-host risk
For this guide, inspect concepts and use safe local processes; do not change system-wide limits or kernel settings to follow a chapter. Advanced container labs should state the runtime, privileges, host OS, and cleanup steps. On macOS, a Linux container runtime commonly involves a Linux virtual machine, so a Linux-specific observation inside a container is not evidence that the macOS kernel implements the same interface directly.
Combine ownership, concurrency, cleanup, measurement, and a precise result contract.
By the end of this chapter
Build a reproducible local worker with bounded inputs
Explain failure handling and distinguish measurements from guarantees
Define useful work and its limits
Build a local tool that counts words in a small, explicit set of UTF-8 text files. The input is a list of paths chosen by the learner, not a recursive scan of the whole computer. Limit the example to a small number of files and a maximum size per file. Each result contains either a count or a clear failure category. A missing file, invalid UTF-8, and a worker exception are not silently converted into a count of zero, because zero is a valid observation for an empty file.
Begin with a pure function that counts words in a supplied string, then add file access with context-managed lifetime. Only after those pieces work should you introduce a bounded worker pool. Keep the concurrency level small and measure before increasing it. File I/O can overlap, but the storage device, page cache, Python runtime, and workload size determine whether concurrency helps. A cached second run should not be compared with an uncached first run as if worker count were the only difference.
A small explicit worker pool with safe temporary inputs python
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from tempfile import TemporaryDirectory
def count_file(path):
if path.stat().st_size > 4096:
raise ValueError("teaching input exceeds size limit")
with path.open(encoding="utf-8") as stream:
return len(stream.read(4097).split())
with TemporaryDirectory() as directory:
paths = [Path(directory) / name for name in ("a.txt", "b.txt")]
paths[0].write_text("learn operating systems", encoding="utf-8")
paths[1].write_text("read and practise", encoding="utf-8")
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(count_file, paths))
print(results)
Expected result
[3, 3]
The size check is appropriate only for these controlled temporary files. For files that other processes can change concurrently, a stat-before-read check has a race: the file can grow after the check. A robust implementation reads a bounded byte sequence, detects overflow, and decodes according to the contract, or uses another explicit snapshot mechanism. That limitation is useful to discover rather than hide. File names and earlier metadata observations do not freeze a file’s future contents.
A bounded work pipeline. An explicit input set enters a small worker pool. Each worker owns its file handle, reports a count or failure, and the caller collects results before cleanup.Scroll horizontally to read the full diagram on a small screen.
Add tests for an empty file, one word, multiple whitespace characters, non-ASCII text, a missing path, invalid encoding, and a too-large input. Make the failure cases observable in returned results or structured exceptions. Verify that the executor is shut down and temporary files can be removed after both success and failure. Do not use an infinite task source with an API that eagerly collects all inputs. The queue or submission strategy must bound pending work as well as the number of running workers.
Measure wall-clock duration using a monotonic performance counter and record file sizes, worker count, runtime, operating system, and whether repeated reads benefit from cache. If two workers are slower for tiny files, explain startup and coordination costs before declaring the operating system broken. The report should include an ownership diagram, acceptance tests, a failure table, and a paragraph stating what remains outside scope: hostile path races, durable database transactions, full sandboxing, and production-grade cancellation.
A reproducible experiment states both its guarantees and its limitations.
Practise before moving on
Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.
14.1 · Practice task
Replace the controlled-file size check with a bounded-read contract suitable for a file that might grow. What should happen after the bound is exceeded?
Hint: Read at most limit plus one byte before decoding or counting.
These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.
Chapter 1 · Meet the operating system without memorizing a list
Solution 1.1
The language runtime or standard-I/O library can buffer output and combine it with later writes. The kernel can buffer or queue work further. A visible language call is not a one-to-one trace of device operations. To investigate timing, identify buffering layers and use documented flush or synchronization behavior rather than assuming the source line is a physical event.
No. The address space can include unmapped gaps, shared mappings, reserved ranges, and pages not currently resident. Virtual size and resident memory measure different things. Interpret the specific operating system’s metrics and workload before concluding there is a leak or a shortage of physical memory.
Chapter 2 · Create, run, wait for, and clean up processes
Solution 2.1
No. On success, the process runs the replacement program. An exec-family call returns to the old code only when it fails, with an error indication appropriate to the API. The PID can remain the same even though the program and address space changed, which is why process identity and program filename are not interchangeable.
Each child consumes scheduling capacity, memory, descriptors, and management overhead. Unlimited creation can exhaust the host or create severe queueing. Use a bounded worker model, admission policy, per-task limits, and a collection/cleanup path. A fast spawn benchmark does not show that unbounded process creation is operationally safe.
Chapter 3 · Understand threads, states, and context switching
Solution 3.1
Yes. The scheduler can interleave execution, and one task can use CPU time while the other waits for I/O. That is concurrency. Actual simultaneous CPU execution requires suitable parallel hardware and runtime support. Distinguishing the two avoids claiming that adding threads necessarily halves computation time.
The scheduler can run either worker first, so the queue may receive 4 then 9 or 9 then 4. Sorting makes the displayed output deterministic because order is irrelevant to this calculation. If order had business meaning, the program would need explicit sequence identifiers or another ordering rule rather than silently sorting it away.
Chapter 4 · Calculate scheduling tradeoffs with small timelines
Solution 4.1
A-then-B completes at 6 and 8, so mean turnaround is 7. B-then-A completes at 2 and 8, so mean turnaround is 5. Total CPU work remains 8 in both. This shows how completion experience can improve without making the processor execute the underlying work faster.
More slices mean more scheduling and context-switch overhead, and tasks can lose cache or translation locality. A smaller quantum may still improve interactive responsiveness. The right tradeoff depends on workload and objectives; measure both responsiveness and overhead rather than optimizing one number in isolation.
Chapter 5 · Build a useful model of virtual memory
Solution 5.1
No. The same virtual address can map to different physical pages in different processes. Intentional shared mappings are possible, but numeric equality alone does not establish them. You need evidence about the mapping and its permissions, not just a printed address.
The object may still have references, the runtime allocator may keep freed memory for future allocations, shared/cached pages may remain accounted, or reclamation may be delayed by implementation details. Check actual object lifetime and repeated-workload behavior. A single resident-memory observation does not identify the cause.
Chapter 6 · Translate addresses and explain page faults
Solution 6.1
The offset is 2,500 − 2×1,024 = 452. The physical address is 7×1,024 + 452 = 7,620. The virtual page number changes into a frame number while the offset stays the same. This arithmetic assumes that the mapping exists and the requested access is permitted.
No. The processor or system can obtain the valid mapping from page-table information and continue without reading the page from storage. A TLB miss can cost time, but it is not equivalent to a major page fault. Determine which event a performance counter actually measures before interpreting it.
Chapter 7 · Use locality to reason about caches and memory pressure
Solution 7.1
A misses, B misses, A hits and becomes recent, C misses and evicts B, and B misses and evicts A. There are four misses. State both the policy and capacity; changing either can change the result. The trace is small enough to verify by drawing the two frame slots after every access.
Additional workers may increase memory pressure, reclaim, page faults, and I/O while adding scheduling overhead. The machine spends more effort moving or waiting for data. Measure useful completion rate and memory-related stalls while varying concurrency. More runnable work is not the same thing as more productive work.
Chapter 8 · Protect shared state with an explicit invariant
Solution 8.1
The invariant spans both balances. Another participant can observe money removed from A before it appears in B, or concurrent transfers can interfere with validation. Protect the full state transition using one appropriate lock or a carefully ordered multi-lock protocol, and ensure all relevant readers follow that protocol. Database transactions are often the appropriate boundary for persistent account data.
The scheduler may not trigger the harmful timing during that run, the runtime may temporarily serialize operations, or the workload may be too small. A proof relies on the language/runtime guarantees and synchronization design. Use deterministic interleaving models to explain failures and stress tools as additional evidence, not as a substitute for an invariant.
Chapter 9 · Wait for a condition without wasting a CPU
Solution 9.1
After waking, the predicate may still be false because another worker consumed the resource or the API allowed a spurious wakeup. The worker must reacquire the lock and recheck the shared condition. Proceeding after one notification without rechecking can read nonexistent work or violate a bound.
The unfinished-task count remains positive, so join can wait indefinitely even after the visible queue is empty. Put task_done in a finally block paired with each successful get, and test exceptional paths. Empty does not imply all retrieved work has been completed.
Chapter 10 · Recognize deadlock, starvation, and unsafe lock ordering
Solution 10.1
Choose a canonical total order on the resource identities and acquire the distinct needed locks in that order in every path. Release them reliably. The guarantee depends on complete adoption: one exceptional path using the opposite order can reintroduce the cycle. A single owner or a larger transaction boundary may be clearer than many independent locks.
No. It may be starvation: other tasks make progress while this one is continually delayed. A deadlock involves a set unable to make required progress because of a wait cycle or equivalent dependency. Diagnose contention, scheduling, and fairness before applying a deadlock remedy that does not address the actual failure.
Chapter 11 · Understand files, names, descriptors, and permissions
Solution 11.1
No. The operating system can reuse an available descriptor number for a different open resource. Code must track ownership and lifetime rather than using an old integer after close. Such stale-handle bugs can accidentally act on an unrelated file or socket.
The process may lack directory search permission on a parent, the path may resolve differently than expected, or ACLs, sandbox rules, mount state, or another access-control mechanism may deny it. Inspect the precise error and path context. Changing only the final file’s mode may not solve the problem and may expose data unnecessarily.
Chapter 12 · Reason about writes, atomic replacement, and crashes
Solution 12.1
No. It flushes the language-level stream buffer toward the underlying operating-system interface. Kernel caches, device caches, ordering, and error handling remain relevant. Stronger durability requires the documented synchronization protocol for the platform and storage stack, and even that depends on its stated hardware assumptions.
Using the same directory normally keeps the temporary and target on the same filesystem and supports the intended replacement operation. Replacing across filesystems may fail or require a different copy procedure without the same atomicity. The directory entry itself can need synchronization for crash durability on applicable systems. Check errors rather than silently falling back to an unsafe partial rewrite.
No. Some bytes may be available, EOF may be observable, or the subsequent operation may need careful nonblocking error handling. The parser must accumulate and frame the message according to the protocol and enforce bounds. Readiness does not supply an application-level message contract.
A quota can throttle execution, the process may wait on storage or a lock, or a dependency may be slow. Inspect the container’s limits, throttling metrics, blocked states, and stage timings. Available host capacity does not prove that this workload has permission or ability to use it.
Chapter 14 · Capstone: a bounded file-analysis worker
Solution 14.1
Open the file in binary mode, read at most limit+1 bytes, reject if more than limit were obtained, and only then decode according to the declared encoding. This bounds this read’s memory use and avoids trusting earlier size metadata. It does not make the path immune to all races or provide a consistent snapshot of arbitrary concurrent edits; document that remaining limitation.
The inputs may be too small, worker setup and coordination may dominate, storage may serialize access, the runtime may limit CPU parallelism, or the second experiment may see different cache state. Measure controlled runs and distinguish CPU time from wall time. The purpose is a correct bounded workflow first, with an evidence-based performance explanation second.
The observation can become stale before use. A bounded read with overflow detection enforces a clearer memory bound, while other race and snapshot concerns still need explicit treatment.
Slowing or blocking producers when downstream capacity is exhausted. Chapter
Blocked state
A state waiting for an event rather than currently eligible CPU execution. Chapter
Concurrency
Overlapping progress of multiple activities across time. Chapter
Condition variable
A waiting mechanism coordinated with a lock and shared-state predicate. Chapter
Context switch
Saving and restoring execution state to change the running activity. Chapter
Control group
A Linux mechanism for hierarchical resource accounting and control. Chapter
Critical section
A protected state transition whose coordination preserves an invariant. Chapter
Deadlock
A dependency state preventing required progress among waiting activities. Chapter
Durability
The promised survival of acknowledged state across specified failures. Chapter
exec
A family of operations replacing the calling process’s program image. Chapter
File descriptor
A process-local integer handle referring to an open resource. Chapter
fork
A Unix-like process-creation operation duplicating a caller’s process context under defined rules. Chapter
Invariant
A condition that must remain true at the boundaries visible to other participants. Chapter
Kernel
The privileged core managing protected operations and shared machine resources. Chapter
Livelock
Ongoing activity that fails to produce useful progress because of repeated reactions. Chapter
Locality
A tendency to reuse recent or nearby data, useful to caching. Chapter
LRU
Least-recently-used replacement, evicting the item unused for the longest recent interval in the model. Chapter
Namespace
A scoped view of selected operating-system resources. Chapter
Page
A fixed-size unit of a virtual-memory mapping. Chapter
Page fault
An exceptional memory-access condition requiring system handling. Chapter
Page frame
A physical-memory slot that can back a virtual page. Chapter
Page table
Translation and protection information mapping virtual pages. Chapter
Parallelism
Simultaneous execution on multiple execution resources. Chapter
PID
A process identifier meaningful within an operating-system or namespace context. Chapter
Process
A running instance with an address space, execution state, and resources. Chapter
Program
Stored instructions and data that can be loaded for execution. Chapter
Quantum
A scheduling time slice in a policy such as round-robin. Chapter
Race condition
An incorrect dependence of an outcome on timing or ordering. Chapter
Readiness
An indication that an I/O operation may currently make progress under its API rules. Chapter
Resident memory
Memory currently present in physical RAM under the platform’s accounting rules. Chapter
Response time
Delay from arrival until a task first receives service in the stated model. Chapter
Starvation
Continued denial of useful progress to one task while others may advance. Chapter
System call
A controlled interface through which a program requests kernel work. Chapter
Thread
An execution context within a process, commonly sharing its address space. Chapter
TLB
A cache of address-translation information. Chapter
Turnaround time
Completion time minus arrival time for a task. Chapter
User space
The less-privileged execution environment for ordinary applications and libraries. Chapter
Virtual address
An address interpreted through a process’s mappings and protection context. Chapter
Working set
The actively needed data over a chosen interval. Chapter
Zombie
A terminated Unix child whose termination record has not yet been collected. Chapter
Read and watch with a purpose
Reading and video library
Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.
Remzi and Andrea Arpaci-Dusseau, University of Wisconsin–Madison · book
Author-hosted chapter reading on virtualization, concurrency, persistence, and security. Link to the authorized chapters; do not mirror their text or figures.
Official lecture schedule with actual video links for processes, page tables, locking, scheduling, and filesystems. The archived course has its own edition.
If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.
Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.