Lecture 16 · Processes and multitasking

Introduction to Computer Systems · Lecture 16。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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:

  1. 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).
  2. Read the process state diagram (running / ready / stopped / terminated) and say what moves a process between states.
  3. Use fork correctly, including its one-call-returns-twice behaviour, and enumerate the possible outputs of a small fork program with a process graph.
  4. Reap children with wait/waitpid, explain zombies, and decode the status word (WIFEXITED, WEXITSTATUS).
  5. 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 fork cheap. 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

SectionIdeaDemo in code/lecture16/
§3fork: one call, two returns; private memory02_fork_two_returns.c
§3process graphs: all possible outputs01_process_graph.py, forksim.py
§4reaping children, zombies, status words03_reaper.c
§5execve: becoming a different program04_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:

  1. 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.
  2. 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 return from main, 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 fork that is immediately followed by execve (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 a once (before the fork, so only one process runs it) and b twice (two processes run it after). a happens-before every b, so the only possible output is abb; bab is impossible.
  • Snippet 2 has two forks → up to four processes, six print events (two as, four bs), and three distinct orderings. Every output begins with a (a process prints its a before it can fork and print b), so bbaabb is 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 like WNOHANG (don’t block — return 0 if no child is ready yet; used in Lecture 17’s SIGCHLD handler).

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:

  1. read a command line;
  2. fork a child;
  3. in the child, execve the requested program (with the parsed argv);
  4. in the parent, wait for 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’s SIGCHLD).

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).
  • fork creates 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/waitpid reap children and decode the status word; unreaped children are zombies that leak table slots.
  • execve replaces 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; fork copies the address space. Use real IPC (pipes, Lecture 18) or shared memory to communicate.
  • Expecting a fixed output order. After a fork the interleaving is up to the scheduler; only the happens-before edges are guaranteed. Draw the process graph.
  • Forgetting to fflush before fork. 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 SIGCHLD handler (Lecture 17).
  • Reading the status wrong. status is a packed word; use WIFEXITED/WEXITSTATUS, not status directly.
  • Code after a successful execve. It never runs. The only reason control returns from execve is failure — always handle that.
  • Calling exit (not _exit) in a child after fork. It may flush inherited stdio buffers a second time.

Exercises

  1. Two returns. Explain how a single fork() call can make the following if (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.
  2. Count the lines. printf("x"); fork(); fork(); printf("y"); — how many x and how many y are printed?

    AnswerOne `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.
  3. Possible or not? For fork(); printf("a"); fork(); printf("b");, is bbaabb a possible output? Why?

    AnswerNo. 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`.)
  4. 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?

    AnswerThe 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.
  5. fork then exec. Why is running a program split into fork + execve instead of a single “spawn(program, args)” call?

    AnswerSo 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.)
  6. Status decode. waitpid fills status and WIFEXITED(status) is false while WIFSIGNALED(status) is true with WTERMSIG(status) == 11. What happened to the child?

    AnswerThe 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 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 full options and the status macros.
  • The csapp.c wrappers (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命令行解释器
← 返回课程目录