Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 16 (Oct 27), slide deck
processes. Reading: CS:APP3e §8.1–§8.4. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro (macOS). These are real Unix process programs; process creation is an OS service, so there is nothing architecture-specific to cross-compile here. Code:code/lecture16/. Reading time: ~85 minutes; ~15 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Define a process as a private logical control flow plus a private address space, and explain how one CPU gives every program the illusion of a machine to itself (context switching, user vs kernel mode).
- Read the process state diagram (running / ready / stopped / terminated) and say what moves a process between states.
- Use
forkcorrectly, including its one-call-returns-twice behaviour, and enumerate the possible outputs of a small fork program with a process graph. - Reap children with
wait/waitpid, explain zombies, and decode the status word (WIFEXITED,WEXITSTATUS). - Load a new program with
execve, and explain how a shell runs a command as fork + exec + wait.
0.2 Prerequisites and scope
- Lectures 11–12 (virtual memory): each process gets its own address space, and copy-on-write is what makes
forkcheap. This lecture is the control-flow half of the same story. - Lecture 5 (the stack,
call/ret): ordinary control flow. This lecture is about control flow that is not ordinary — the first kind of exceptional control flow (ECF). - In scope: CS:APP §8.1–§8.4 — the process abstraction, user/kernel mode, context switching, and the process-control system calls
fork,exit,wait/waitpid,execve. - Out of scope here: exceptions and signals (Lecture 17), and the shell lab’s actual job control (we describe the mechanism, never lab solutions).
0.3 Section → code map
| Section | Idea | Demo in code/lecture16/ |
|---|---|---|
| §3 | fork: one call, two returns; private memory | 02_fork_two_returns.c |
| §3 | process graphs: all possible outputs | 01_process_graph.py, forksim.py |
| §4 | reaping children, zombies, status words | 03_reaper.c |
| §5 | execve: becoming a different program | 04_exec.c |
1. Control flow, and exceptional control flow
Since Lecture 3 the CPU has done one thing forever: read the instruction at the program counter, run it, advance to the next. The only ways the PC has moved other than “+1 instruction” were jumps, branches, and call/ret (Lecture 4–5). All of those are planned by your program: the control flow is a property of your code.
That is not enough to build a real system. The machine must also react to things your code did not plan for and cannot see coming:
- the disk finishes a read, or a packet arrives (an external interrupt);
- the program divides by zero or touches an unmapped page (a fault);
- the program asks the kernel to do something it is not allowed to do itself, like read a file (a trap / system call);
- you press Ctrl-C.
The general name for “control flow that is not an ordinary jump, branch or call” is exceptional control flow (ECF). It exists at every level of the system, and Unit V is a tour of it. This lecture covers the first and most important consequence of ECF: the operating system can take the CPU away from your program and give it to another, and your program need never know. That mechanism is what turns one CPU into the illusion of a private machine for every program — a process.
2. The process abstraction
2.1 What a process is
A process is the operating system’s answer to “what is a running program?”. It bundles two illusions:
- A private logical control flow. It looks as if your program has the CPU entirely to itself: a steady sequence of instructions, PC advancing, from start to exit. In reality the CPU is time-sliced among many processes, but each one’s flow is preserved across the gaps.
- A private address space. It looks as if your program owns all of memory: the same addresses (
0x0…up) every run, no other program able to read or clobber it. In reality virtual memory (Lectures 11–12) maps each process’s addresses to different physical frames.
Put together: a process is a program in execution, with the illusion that it has the whole machine. Everything in this unit is about where that illusion leaks.
2.2 How one CPU runs many processes: context switching
A single core runs one instruction stream at a time. The illusion of many comes from multitasking: the kernel runs process A for a few milliseconds, then performs a context switch — it saves A’s context (all registers, including the PC and stack pointer, plus the pointer to A’s page tables) into memory, loads B’s saved context, and resumes B exactly where it last stopped. B has no idea it was ever paused.
Two processes thus run concurrently (their flows overlap in time) even on one core, because the core alternates between them faster than you can see. On a multicore machine they may also run in parallel (literally at the same instant) — concurrency is the general idea, parallelism the special case (Lecture 24). Context switches are triggered by ECF: a timer interrupt (A’s slice is up), or A blocking on I/O, or a system call.
2.3 User mode and kernel mode
Context switching, page tables, and talking to devices are too dangerous to let any program do. The CPU therefore runs in one of two modes, controlled by a bit the kernel sets:
- User mode (your program): cannot execute privileged instructions (halt, set page tables, do raw device I/O) and cannot touch kernel memory. Attempting to is a fault.
- Kernel mode (the OS): can do everything.
Your program enters kernel mode only through controlled doors: a system call (a trap you issue on purpose, e.g. read), or an exception (a fault or interrupt the hardware raises). The kernel does the privileged work and returns you to user mode. This is why fork, wait, execve and friends are system calls, not library functions you could have written: only the kernel can create an address space or schedule a flow.
2.4 The process state diagram
At any moment a process is in one of a few states (CS:APP’s simplified diagram):
- Running — currently executing on a CPU.
- Ready (runnable) — able to run, waiting for the scheduler to give it a core.
- Blocked / waiting — cannot run until some event occurs (I/O completes, a child exits, a signal arrives).
- Stopped — suspended (e.g. by a job-control signal), will not run until told to continue (Lecture 17).
- Terminated — finished (via
returnfrommain,exit, or a fatal signal), but may linger as a zombie until reaped (§4).
Scheduling moves a process between running and ready; blocking I/O or wait moves it to blocked; the completing event moves it back to ready.
3. Creating a process: fork
3.1 One call, two returns
fork() creates a new process — the child — that is a near-duplicate of the caller — the parent. The famous strangeness: you call fork once, and it returns twice, once in each process. The two returns differ only in the value:
- the parent receives the child’s process id (a positive
pid_t); - the child receives 0.
That is how the two copies, which are otherwise identical, tell themselves apart. At the instant of the two returns, the child has a copy of the parent’s entire state: the same variables with the same values, the same open files, the same next instruction. From then on each has its own private memory; a change in one is invisible to the other.
02_fork_two_returns.c makes all of this concrete:
[before] one process, pid=68656, is about to call fork()
[child ] fork() returned 0; my pid=68657, my parent=68656, x=101
[parent] fork() returned 68657 (child's pid); my pid=68656, x=1100
[parent] note: child saw x=101, parent sees x=1100 -- memory was COPIED, not shared
One printf("[before]") ran, but two processes continued past the fork(). Both started from x = 100; the child added 1 (→ 101) and the parent added 1000 (→ 1100), and neither saw the other’s change. The child’s parent id (getppid()) is the parent’s pid, confirming the lineage.
Why is the copy cheap? Duplicating a whole address space sounds expensive. Lecture 12’s copy-on-write is the trick: parent and child first share the same physical pages read-only; the kernel copies a page only when one of them writes to it. A
forkthat is immediately followed byexecve(the common case, §5) barely copies anything.
3.2 fflush before fork
Notice the fflush(stdout) before the fork. stdout is line-buffered to a terminal but fully buffered to a pipe or file. Any text still sitting in the buffer at the moment of fork is duplicated into the child’s buffer and printed again when each process flushes — so the “[before]” line could appear twice. Flushing before forking empties the buffer so there is nothing to duplicate. (The child also calls _exit, not exit, to avoid flushing inherited buffers a second time.)
3.3 Process graphs: what can a fork program print?
Because parent and child run concurrently, the order in which their output lines appear is not determined — any single run shows one order, chosen by the scheduler. The exam question is therefore: what are all the possible outputs? The tool is the process graph (CS:APP §8.4.2): draw each process’s statements as a chain (program order), and each fork as a branch. The possible outputs are exactly the orderings consistent with that partial order (its topological sorts).
01_process_graph.py (built on forksim.py) builds the graph and enumerates them mechanically, so you can check a hand analysis:
== snippet 1: printf(a); fork(); printf(b); ==
forks=1 processes(max)=2 print-events=3 distinct outputs=1
possible outputs: abb
== snippet 2: fork(); printf(a); fork(); printf(b); ==
forks=2 processes(max)=4 print-events=6 distinct outputs=3
possible outputs: aabbbb, ababbb, abbabb
OK 'abb' possible? True 'bab' possible? False
OK 'aabbbb' possible? True 'bbaabb' possible? False
- Snippet 1 prints
aonce (before the fork, so only one process runs it) andbtwice (two processes run it after).ahappens-before everyb, so the only possible output isabb;babis impossible. - Snippet 2 has two forks → up to four processes, six print events (two
as, fourbs), and three distinct orderings. Every output begins witha(a process prints itsabefore it can fork and printb), sobbaabbis impossible.
forksim.py is a deterministic teaching tool (it models only print and fork, and sorts every result so its output is byte-identical under Python 3.9 and 3.13). It is not a lab deliverable.
4. Ending a process, and reaping: exit, wait, zombies
4.1 Terminating
A process ends when main returns, when it calls exit(code) (or _exit), or when it is killed by a signal (Lecture 17). The low 8 bits of the exit code are its exit status, available to its parent.
4.2 Zombies and reaping
A terminated process does not immediately disappear. It becomes a zombie: it runs nothing and holds no memory, but the kernel keeps a small record of it — chiefly how it died — until the parent collects that record. Collecting it is called reaping, done with wait or waitpid, and it frees the zombie’s slot in the process table.
Why keep the corpse at all? So the parent can find out whether the child succeeded. If a parent never reaps, zombies accumulate and leak process-table entries — a real bug in long-running servers. (If the parent itself exits first, the orphaned children are re-parented to init/launchd, which reaps them.)
03_reaper.c forks five children with distinct exit codes and reaps them all:
[parent] pid=68659 creating 5 children...
[parent] reaped 5 children (sorted by pid):
child pid=68660 exited with status 10
child pid=68661 exited with status 11
child pid=68662 exited with status 12
child pid=68663 exited with status 13
child pid=68664 exited with status 14
[parent] all children reaped; no zombies remain
4.3 wait, waitpid, and the status word
wait(&status)blocks until any one child terminates, reaps it, and returns its pid.waitpid(pid, &status, options)is the general form: wait for a specific child (or any, with-1), with options likeWNOHANG(don’t block — return 0 if no child is ready yet; used in Lecture 17’sSIGCHLDhandler).
The children finish in an unpredictable order (they race), so waitpid(-1,…) returns them in finish order; the demo records (pid, status) and sorts by pid for a stable report. status is not the raw exit code — it is a packed word you decode with macros: WIFEXITED(status) (did it exit normally?), WEXITSTATUS(status) (the code it passed to _exit), WIFSIGNALED/WTERMSIG (killed by a signal, and which). The demo decodes 10..14 correctly.
5. Running a different program: execve
fork copies the current program. To run a different one, the child calls an exec function, which replaces its entire memory image with a new program loaded from disk — new code, data, heap and stack — while keeping the same pid and open files. On success execve does not return: there is no old code to return to.
char *argv[] = { "/bin/echo", "hello", "from execve", NULL };
execve(argv[0], argv, environ); /* returns ONLY on failure */
perror("execve"); /* so reaching here means it failed */
04_exec.c forks, execs /bin/echo in the child, and waits:
[parent] pid=68666; about to fork+exec /bin/echo
hello from execve <- printed by /bin/echo, the NEW image
[parent] child (/bin/echo) exited with status 0
[parent] note: the child never printed anything of its OWN after execve
The "hello from execve" line is produced by the echo program, now running in the child’s process; the C code we wrote after execve never ran, because its code was replaced. argv[] became echo’s command-line words (argv[0] is conventionally the program name), and environ (the environment variables) was carried into the new program.
5.1 How a shell runs a command
Everything above assembles into the core loop of a shell:
- read a command line;
forka child;- in the child,
execvethe requested program (with the parsedargv); - in the parent,
waitfor the child if the command is in the foreground (or record it as a background job and reap it later — the subject of the shell lab and Lecture 17’sSIGCHLD).
fork + exec + wait is the whole mechanism. The reason it is split into two calls (rather than one “spawn”) is flexibility: between the fork and the exec, the child can adjust its inherited state — redirect stdout to a file, close descriptors, change the working directory — which is exactly how the shell implements >, < and pipes (Lecture 18).
Summary
- A process is a private logical control flow + a private address space: the illusion that a program owns the whole machine. Context switching (save registers + page-table pointer, load another’s) multiplexes one CPU among many; the user/kernel mode bit protects the privileged machinery.
- The process state diagram: running ⇄ ready, blocked on an event, stopped, terminated (then a zombie until reaped).
forkcreates a near-duplicate child: one call, two returns (child gets 0, parent gets the child’s pid), with copied, not shared memory (cheap via copy-on-write). Concurrency makes the output order undetermined — a process graph gives all possible outputs.wait/waitpidreap children and decode the status word; unreaped children are zombies that leak table slots.execvereplaces the process image with a new program and does not return on success. fork + exec + wait is how a shell runs a command.
Common pitfalls
- Assuming parent and child share variables. They do not;
forkcopies the address space. Use real IPC (pipes, Lecture 18) or shared memory to communicate. - Expecting a fixed output order. After a
forkthe interleaving is up to the scheduler; only the happens-before edges are guaranteed. Draw the process graph. - Forgetting to
fflushbeforefork. Buffered stdout is duplicated into the child and printed twice to a pipe or file. - Not reaping children. Every child must be waited for, or it becomes a leaking zombie — in a server, use a
SIGCHLDhandler (Lecture 17). - Reading the status wrong.
statusis a packed word; useWIFEXITED/WEXITSTATUS, notstatusdirectly. - Code after a successful
execve. It never runs. The only reason control returns fromexecveis failure — always handle that. - Calling
exit(not_exit) in a child afterfork. It may flush inherited stdio buffers a second time.
Exercises
-
Two returns. Explain how a single
fork()call can make the followingif (pid == 0) … else …run both branches across the two processes.Answer
`fork` returns twice — 0 in the child, the child's pid in the parent. Each process takes one branch: the child (pid==0) the `if`, the parent (pid>0) the `else`. One source `if`, two processes, both branches executed, once each. -
Count the lines.
printf("x"); fork(); fork(); printf("y");— how manyxand how manyyare printed?Answer
One `x` (printed before any fork, by the single original process) and four `y` (two forks → 2²=4 processes, each printing `y` after). The `forksim` model confirms 1 + 4 = 5 print events. -
Possible or not? For
fork(); printf("a"); fork(); printf("b");, isbbaabba possible output? Why?Answer
No. Each process prints its `a` *before* it forks and prints `b`, so the very first character printed is always an `a`. An output starting with `b` is impossible. (The enumerator lists only `aabbbb`, `ababbb`, `abbabb`.) -
Zombie. A parent forks a child that exits immediately; the parent then loops forever without calling
wait. What is the child’s state, and what resource leaks?Answer
The child is a **zombie**: terminated but not reaped. It uses no CPU or memory, but it holds a process-table slot (and its exit status) until reaped. A parent that never reaps leaks these slots; here they leak until the parent dies and `init`/`launchd` reaps the orphan. -
fork then exec. Why is running a program split into
fork+execveinstead of a single “spawn(program, args)” call?Answer
So the child can modify its inherited environment *between* the fork and the exec — redirect descriptors (`>`/`<`/pipes), close files, change directory, set signal dispositions — before the new program starts. One combined call could not express those per-launch adjustments cleanly. (This is also why copy-on-write matters: the fork is almost free when an exec follows.) -
Status decode.
waitpidfillsstatusandWIFEXITED(status)is false whileWIFSIGNALED(status)is true withWTERMSIG(status) == 11. What happened to the child?Answer
The child was **killed by a signal**, not a normal exit; signal 11 is `SIGSEGV` (a segmentation fault). So the child dereferenced bad memory (or similar) and the kernel terminated it. `WEXITSTATUS` would be meaningless here; the signal number is the information.
The related lab
The shell lab (tshlab/shlab) has you implement a tiny shell: parse a command line, fork+execve to run programs, support foreground/background jobs, and reap children in a SIGCHLD handler (Lecture 17). This lecture supplies the process-control half; Lecture 17 supplies the signal half. Per the course’s academic-integrity policy, these notes contain no lab solutions — the demos here (fork, reaping, exec in isolation) teach the mechanisms, not the lab’s shell, and deliberately omit its job-control bookkeeping and I/O interface.
Further reading
- CS:APP3e §8.1–§8.4 (exceptional control flow, processes, system-call error handling, process control) and practice problems 8.1–8.4 — the process-graph problems match demo 01.
man 2 fork,man 2 waitpid,man 2 execve— the authoritative semantics, including the fulloptionsand the status macros.- The
csapp.cwrappers (Fork,Wait,Waitpid) in the textbook’s support code show the standard “check every system call” style used in the labs.
Preview of Lecture 17: Exceptional control flow — signals
fork/wait/exec are synchronous process control. Lecture 17 covers the asynchronous side of ECF: exceptions (interrupts, traps, faults, aborts) at the hardware/kernel level, and signals — the kernel’s way of delivering a software “interrupt” to a process (Ctrl-C, a dead child, a bad memory access). You will see why almost nothing is safe to call inside a signal handler, why you must block signals around shared state, why you cannot count SIGCHLDs, and how setjmp/longjmp jump non-locally out of a deep call chain.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| exceptional control flow (ECF) | 异常控制流 |
| process | 进程 |
| logical control flow | 逻辑控制流 |
| address space | 地址空间 |
| multitasking / time slicing | 多任务 / 时间片轮转 |
| context switch | 上下文切换 |
| context (of a process) | 进程上下文 |
| concurrency / parallelism | 并发 / 并行 |
| user mode / kernel mode | 用户态 / 内核态 |
| privileged instruction | 特权指令 |
| system call | 系统调用 |
| scheduler | 调度器 |
| process state (running/ready/blocked/stopped/terminated) | 进程状态(运行/就绪/阻塞/停止/终止) |
fork | 创建子进程 |
| parent / child process | 父进程 / 子进程 |
| process id (pid) | 进程号 |
| copy-on-write | 写时复制 |
| process graph | 进程图 |
| happens-before | 先于发生(偏序) |
| topological sort / linear extension | 拓扑排序 / 线性扩展 |
exit / _exit | 退出 |
| exit status | 退出状态 |
| zombie | 僵尸进程 |
| reaping | 回收(子进程) |
wait / waitpid | 等待子进程 |
WIFEXITED / WEXITSTATUS | 退出判定宏 / 退出码宏 |
WNOHANG | 非阻塞等待选项 |
| orphan process | 孤儿进程 |
execve / exec family | 加载并执行新程序 |
| program image | 程序映像 |
argv / environ | 参数向量 / 环境变量 |
| shell | 命令行解释器 |