Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 17 (Oct 29), slide deck
ecf. Reading: CS:APP3e §8.5–§8.8. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro (macOS). Signals are a kernel service, so there is nothing architecture-specific to cross-compile. Code:code/lecture17/. 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:
- Classify the four kinds of hardware/kernel exceptions — interrupts, traps, faults, aborts — by cause, who triggers them, and whether control resumes.
- Explain signals as software exceptions: how they are sent (
kill, Ctrl-C, the kernel), received, and the pending and blocked bit-sets that govern delivery, plus default actions. - Write a correct signal handler: keep it async-signal-safe, use
volatile sig_atomic_tfor flags, save/restoreerrno, and reap in a loop in aSIGCHLDhandler. - State why you cannot count signals (they do not queue), and demonstrate the loss.
- Use
sigprocmaskto block signals around a shared-state update, and usesetjmp/longjmpfor a nonlocal jump out of a deep call chain.
0.2 Prerequisites and scope
- Lecture 16: processes,
fork/wait/exec.SIGCHLDis how the asynchronous reaping of Lecture 16’s children actually happens. - Lecture 5: the stack and
call/ret— a handler runs on the process’s stack, “between” ordinary instructions. - In scope: CS:APP §8.5–§8.8 — the exception taxonomy, the signal mechanism, handler safety, blocking signals, and nonlocal jumps.
- Out of scope / policy: the shell lab’s job control. These notes describe the signal mechanisms the lab uses but contain no lab solutions.
0.3 Section → code map
| Section | Idea | Demo in code/lecture17/ |
|---|---|---|
| §3 | correct SIGCHLD reaping (loop + WNOHANG) | 01_sigchld_reaper.c |
| §3 | signals do not queue — you cannot count them | 02_lost_signals.c |
| §5 | nonlocal jump out of a deep call chain | 03_setjmp_longjmp.c |
1. The exception taxonomy
Lecture 16 introduced exceptional control flow: control transfers that are not ordinary jumps, branches or calls. At the lowest level, ECF is implemented by exceptions — an abrupt transfer to the kernel in response to some event. When an exception occurs, the processor stops the current instruction stream, switches to kernel mode, and jumps (via the exception table, indexed by an exception number) to a kernel routine, the handler. CS:APP sorts exceptions into four kinds:
| Kind | Cause | Synchronous? | Returns to… |
|---|---|---|---|
| Interrupt | external device (timer, disk, NIC) | asynchronous | the next instruction |
| Trap | an intentional request (a system call, int/syscall) | synchronous | the next instruction |
| Fault | a recoverable error (page fault, divide, protection) | synchronous | the faulting instruction (retry) or abort |
| Abort | an unrecoverable error (hardware failure) | synchronous | never — the program dies |
The distinctions matter:
- Synchronous vs asynchronous. A trap/fault/abort is caused by the current instruction (synchronous); an interrupt arrives from outside, unrelated to what the CPU is running (asynchronous). The timer interrupt is what lets the kernel pre-empt a running process (Lecture 16’s context switch).
- Fault vs trap is the classic exam question. A trap is deliberate and always resumes at the next instruction (the system call did its job). A fault is an error on the current instruction; the handler either fixes the condition and re-runs the same instruction (a page fault pages the data in, then retries — the whole point of demand paging, Lecture 11) or, if it cannot, escalates to killing the program.
The kernel is thus the universal handler sitting underneath every process. Signals are how it passes certain exceptions back up to a process in a form the process can handle itself.
2. Signals: software exceptions delivered to a process
2.1 The abstraction
A signal is a small integer message — “a signal of type N occurred” — delivered to a process to notify it of a system-level event. There are a few dozen types; a handful you will meet constantly:
| Signal | Number* | Default action | Typical cause |
|---|---|---|---|
SIGINT | 2 | terminate | you pressed Ctrl-C |
SIGKILL | 9 | terminate (cannot be caught/ignored) | kill -9 |
SIGSEGV | 11 | terminate (core) | invalid memory reference |
SIGCHLD | 20/17 | ignore | a child stopped or terminated |
SIGSTOP/SIGCONT | — | stop / continue (STOP uncatchable) | job control (Ctrl-Z, fg) |
SIGUSR1/SIGUSR2 | — | terminate | application-defined |
*Numbers differ across systems (that is why you use the names). Each signal has a default action — terminate, terminate-and-dump-core, ignore, stop, or continue — that happens unless the process installs its own handler. SIGKILL and SIGSTOP are special: a process can neither catch nor ignore them, so there is always a way to kill or stop any process.
2.2 Sending and receiving
Two independent steps, possibly far apart in time:
- Sending. A signal is sent by the kernel (a child died →
SIGCHLD; you touched bad memory →SIGSEGV; the terminal driver on Ctrl-C →SIGINT) or by one process to another withkill(pid, sig)(thekillcommand and shell job control use this). Sending a signal sets the pending bit for that type in the destination process. - Receiving. A process receives a pending signal when the kernel, on its way back to that process’s user code, notices the pending bit and forces the process to react: take the default action, ignore it, or run the installed handler. A handler runs in user mode, on the process’s stack, “between” two ordinary instructions, then returns to where the process was.
2.3 Pending and blocked sets
The kernel keeps two bit-vectors per process:
- pending — signals sent but not yet received.
- blocked (the signal mask) — signals the process has temporarily told the kernel not to deliver.
Two rules follow, and they are the source of most signal bugs:
- A blocked signal stays pending and is delivered once unblocked. (This is how you create a critical section, §4.)
- Pending is a single bit per type — signals do not queue. If a signal of type N is already pending and another N arrives, the second is discarded: the bit is already 1. At most one signal of each type can be pending. This is why you cannot count signals (§3.2), and why a
SIGCHLDhandler must reap all ready children, not one.
3. Writing a correct signal handler
A handler is uniquely hard to write because it runs asynchronously: it can interrupt your main code at any instruction, including in the middle of malloc, printf, or updating a data structure. Three rules.
3.1 Keep it async-signal-safe
A handler may call only async-signal-safe functions — ones guaranteed to work when called from a point where the main program might be halfway through the same function. printf, malloc, and most of the C library are not safe (a handler that calls malloc while the main code was inside malloc can corrupt the heap). The safe set is small: write, _exit, waitpid, kill, and the like. The practical pattern is: a handler sets a flag (or drains a queue) and returns; the main loop does the real work. Shared flags must be:
static volatile sig_atomic_t flag = 0; /* the only portable handler<->main variable */
volatile stops the compiler from caching the variable in a register (the handler changes it invisibly to the main code), and sig_atomic_t is a type the platform reads/writes in one uninterruptible step. A handler must also save and restore errno, because it runs between main-code instructions that may be about to read errno.
3.2 You cannot count signals — so reap in a loop
Because signals do not queue (§2.3), a handler must never assume one delivery per event. 02_lost_signals.c makes the loss visible: a child fires one million SIGUSR1 at the parent; the parent counts how many its handler actually runs for:
[parent] sent 1000000, received 87042 (8.7042% delivered)
[parent] the rest were MERGED: a pending SIGUSR1 cannot stack
Only ~8–9% survive on this machine (and the fraction is smaller on a slower one): while the parent handles one SIGUSR1, the thousands fired meanwhile all collapse into the single pending bit. The count varies run to run (85k–91k across five runs) but the vast majority are always lost. Signals report that something happened, never how many times.
The direct consequence for reaping: when several children die at once, their SIGCHLDs merge into possibly one delivery, so the handler must reap every ready child. 01_sigchld_reaper.c does it the correct way — a loop with waitpid(-1, …, WNOHANG) until no child is ready:
while ((pid = waitpid(-1, NULL, WNOHANG)) > 0)
reaped++; /* drain ALL ready children per delivery */
[parent] pid=P forking 5 children
[parent] handler reaped 5 children; none leaked as zombies
All five are reaped even though fewer than five SIGCHLDs may have been delivered. A reap-exactly-one handler would have leaked zombies — a real, graded bug in the shell lab.
3.3 Install handlers with sigaction
Install handlers with sigaction, not the older signal() (whose semantics vary across systems). Set sa_mask to block other signals during the handler, and typically SA_RESTART so interrupted system calls are retried where possible. (signal() is kept in textbook examples for brevity; sigaction is what the lab wants.)
4. Blocking signals around shared state: sigprocmask
Because a handler can fire between any two instructions, a main program that shares data with its handler has a race: the signal might arrive while the main code is halfway through updating the shared structure. The fix is a critical section: temporarily block the signal, do the update, then unblock. sigprocmask edits the blocked set:
sigset_t mask, prev;
sigemptyset(&mask); sigaddset(&mask, SIGCHLD);
sigprocmask(SIG_BLOCK, &mask, &prev); /* enter: SIGCHLD can't fire now */
/* ... safely add the new child to the job list ... */
sigprocmask(SIG_SETMASK, &prev, NULL); /* leave: restore previous mask */
The classic shell bug this prevents: the parent forks a child and then adds it to its job list, but the child dies and the SIGCHLD handler (which removes the job) runs before the parent added it — deleting a job that was never recorded, then leaving a zombie. Blocking SIGCHLD from just before the fork until just after the job is recorded closes the window. (A blocked signal is not lost — it stays pending and is delivered when unblocked.) The shell lab grades exactly this; the mechanism is here, the solution is not.
5. Nonlocal jumps: setjmp / longjmp
The last form of ECF is entirely within one process and under your control. return unwinds one frame; sometimes you must leap out of a deep call chain in one step — an error found five calls down, recovered at the top — without every intermediate function checking and forwarding an error code. setjmp/longjmp do that:
setjmp(buf)saves the current register/stack state intobufand returns 0.longjmp(buf, v), called anywhere later, restores that state, so control reappears at thesetjmpcall, which this time returnsv(nonzero).
It is try/throw/catch for C: setjmp is the try, longjmp the throw, the setjmp != 0 branch the catch. 03_setjmp_longjmp.c sums the digits of a string and bails out via longjmp on a non-digit, two calls deep:
[try] parsing "345" (all digits) -> sum = 12
[try] parsing "3x5" (has a non-digit)
sum_digits: adding '3'
sum_digits: adding 'x'
digit_value: 'x' is not a digit -- longjmp back to main
[catch] recovered via longjmp with code 42; the deep call was abandoned cleanly
[done] program continues normally after recovery
The second parse jumps straight from digit_value back to main’s setjmp, skipping the rest of sum_digits and the “never reached” line; setjmp, which first returned 0, now “returns” 42 — one call site, two returns. Sharp edges: a local in the setjmp-calling function may hold an indeterminate value after a longjmp unless marked volatile; longjmp must target a frame that is still active; and using it to leave a signal handler (siglongjmp) needs extra care. Use it sparingly, for genuine nonlocal error recovery.
Summary
- Exceptions are the low-level mechanism of ECF: interrupts (asynchronous, external), traps (deliberate system calls, resume at the next instruction), faults (error on the current instruction — retry it or abort), aborts (fatal). The kernel is the universal handler.
- A signal is a software exception delivered to a process. It is sent (sets the pending bit) and later received (default action, ignore, or run a handler). The kernel keeps a pending set and a blocked mask per process.
- Signals do not queue: at most one of each type is pending, so a burst is mostly merged (measured: ~90% of a million sent were lost). You cannot count signals; a
SIGCHLDhandler must reap every ready child in aWNOHANGloop. - A handler must be async-signal-safe (set a
volatile sig_atomic_tflag and return; save/restoreerrno; install withsigaction).sigprocmaskblocks a signal to protect a shared-state update (and a blocked signal stays pending, not lost). setjmp/longjmpjump non-locally out of a deep call chain — C’stry/catch.
Common pitfalls
- Reaping one child per
SIGCHLD. Several deaths merge into one signal; reap in awhile (waitpid(-1,…,WNOHANG) > 0)loop or leak zombies. - Counting signals. They do not stack; a counter in a handler undercounts wildly. Drain state instead (reap all, read all available input).
- Calling unsafe functions in a handler.
printf/mallocin a handler can deadlock or corrupt state. Usewrite/_exit/waitpid; set a flag and let the main loop act. - Forgetting
volatile sig_atomic_t. A plain flag may be cached in a register and the handler’s change never seen; a non-atomic type may be read half-updated. - Not saving
errno. A handler that makes a system call clobbers theerrnothe main code was about to read. - The fork/job-list race. Add a child to shared state with
SIGCHLDblocked (viasigprocmask) around theforkand the update. longjmpto a dead frame. The function that calledsetjmpmust still be active; and locals needvolatileto survive alongjmpreliably.
Exercises
-
Fault or trap? A program executes a
syscall/read, and separately dereferences a null pointer. Which is a trap and which a fault, and where does each resume?Answer
The `read` is a **trap** (a deliberate system call): it resumes at the *next* instruction after the kernel does the I/O. The null dereference is a **fault** (`SIGSEGV`): the handler would resume at the *faulting* instruction if the fault were fixable — here it is not, so the process is terminated. -
How many deliveries? A process sends another 100
SIGUSR1in a tight loop while the receiver is busy. Roughly how many times does the receiver’s handler run?Answer
Far fewer than 100 — possibly just a handful or even 1. A pending `SIGUSR1` cannot stack, so signals arriving while one is pending are discarded. The exact number is a race (demo 02 delivered ~8–9% of a million), but "100" is never the answer. -
The reaping loop. Why
while (waitpid(-1,…,WNOHANG) > 0)and not a singlewaitpidin aSIGCHLDhandler?Answer
Because several children can die between deliveries and their `SIGCHLD`s merge into one. One `waitpid` reaps one child and leaves the rest as zombies; the loop drains every ready child. `WNOHANG` makes the final call (no child ready) return 0 instead of blocking. -
Why
volatile? A handler setsdone = 1;mainloopswhile (!done);. With optimization, the loop never ends. Why, and what fixes it?Answer
The compiler proves `done` is not changed *in the loop* and caches it in a register, never re-reading memory, so it never sees the handler's write. Declaring `done` as `volatile sig_atomic_t` forces a fresh load each iteration (and guarantees atomic access), so the handler's change is seen. -
The window. In a shell, why block
SIGCHLDaroundfork+ “add child to job list”?Answer
Without blocking, the child can die and the `SIGCHLD` handler run — removing the job from the list — *before* the parent adds it. The parent then adds a job that is already dead (never reaped from the list) or deletes nothing and leaves a zombie. Blocking `SIGCHLD` until the job is recorded closes the race; the still-pending signal is delivered right after. -
setjmp’s two returns. After
int r = setjmp(buf);, how do you tell the first pass from alongjmparrival, and what value doeslongjmp(buf, 0)actually deliver?Answer
`setjmp` returns **0** on the initial call and the `longjmp` value on arrival, so `r == 0` is the first pass and `r != 0` is a jump. `longjmp(buf, 0)` is special-cased: it delivers **1**, not 0, so the "arrived via longjmp" branch is never mistaken for the first pass.
The related lab
The shell lab (tshlab/shlab) is where signals become real: a SIGCHLD handler reaps background jobs, SIGINT/SIGTSTP are forwarded to the foreground job, and sigprocmask guards the job list against the fork/reap race. It is the direct sequel to Lecture 16’s process control. Per the course’s academic-integrity policy these notes include no lab solutions; the demos here (a reaping loop, the lost-signal burst, a nonlocal jump) teach the mechanisms in isolation, without the lab’s job table, parsing, or I/O.
Further reading
- CS:APP3e §8.5–§8.8 (exceptions, signals, nonlocal jumps) and practice problems 8.5–8.10; the
sigprocmaskrace is worked in detail in §8.5. man 2 sigaction,man 2 sigprocmask,man 7 signal— the authoritative semantics, the async-signal-safe function list, and the per-signal default actions.- W. R. Stevens & Rago, Advanced Programming in the Unix Environment, chapter 10 — the definitive practical treatment of signals.
Preview of Lecture 18: System-level I/O
Unit V (exceptional control flow) ends here. Unit VI opens with system-level I/O: the Unix open/read/write/close calls underneath every printf, file descriptors and how fork shares them, short counts and the robust-I/O pattern, file metadata (stat), and how dup2 implements shell redirection. The SIGCHLD/fork machinery of Lectures 16–17 plus I/O redirection is everything a shell needs.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| exception | 异常 |
| exception table / exception number | 异常表 / 异常号 |
| interrupt | 中断 |
| trap | 陷阱(自陷) |
| fault | 故障 |
| abort | 终止(不可恢复) |
| synchronous / asynchronous | 同步 / 异步 |
| handler | 处理程序 |
| signal | 信号 |
SIGINT / SIGKILL / SIGSEGV / SIGCHLD | 中断/强杀/段错误/子进程信号 |
SIGSTOP / SIGCONT | 停止 / 继续信号 |
| default action | 默认动作 |
| sending a signal | 发送信号 |
| receiving a signal | 接收信号 |
| pending (set) | 待处理(信号集) |
| blocked (set) / signal mask | 阻塞(信号集) / 信号掩码 |
kill | 发送信号(系统调用) |
| signal handler | 信号处理函数 |
| async-signal-safe | 异步信号安全 |
volatile sig_atomic_t | 易变原子类型 |
| reentrant | 可重入 |
errno (save/restore) | 错误号(保存/恢复) |
sigaction | 安装信号处理(系统调用) |
SA_RESTART | 重启被中断系统调用标志 |
waitpid / WNOHANG | 等待子进程 / 非阻塞选项 |
sigprocmask | 修改信号掩码 |
| critical section / race | 临界区 / 竞态 |
| nonlocal jump | 非局部跳转 |
setjmp / longjmp | 保存/恢复跳转点 |
jmp_buf | 跳转缓冲区 |