1.2 Shell, git, make, processes: exit codes, signals, environment, pipes
Almost everything a system does outside its own code is done by processes deciding things from small integers. A CI gate runs commands and decides pass or fail by their exit status. C code is built by a Makefile that decides what to recompile from file times. A Rust engine and a Go gateway run as processes that Kubernetes stops by sending SIGTERM and, 30 seconds later, SIGKILL. A server that ignores SIGTERM loses in-flight requests; a build that does not track headers ships objects compiled against an old struct layout; a script that ignores a failing command in a pipe reports green on a broken build.
Concepts from other sections (3)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- SIGKILL: an uncatchable signal that ends a process between two instructions, leaving only what is on disk. Read more: 12.3 The durable server is SIGKILLed in a loop during a corpus build in Systems Engineering
- graceful shutdown: stop accepting, let in-flight work finish within a bound, then exit 0. Read more: 1.9 Async Rust and tokio: futures, tasks, channels, cancellation, hyper
- pid 1: the first process in a pid namespace, to which the kernel does not apply
SIGTERM’s default action. Read more: 1.7 Containers and Kubernetes: images, layers, Pods, Deployments, Services, Helm, kind
This section teaches the process model those all share, on two small artifacts that run in seconds. The first is a Makefile for a given two-file C program (main.c, greet.c, greet.h). The second is worker.sh, a script that holds a lock file, traps SIGTERM and SIGINT, cleans up, and exits 128 plus the signal number. Like the other primers, it is an exercise rather than part of a system, so there is no contract file.
To run the examples you need a terminal with bash, make, cc, and git. Read Python and numpy first if you are following the primers in order.
Learning objectives
- Read and use exit statuses, including the convention for signals, to control scripts and pipelines.
- Write a bash trap that cleans up and exits promptly on SIGTERM and SIGINT, even during a long wait.
- Detect and recover a stale lock left by a process killed with SIGKILL.
- Write a Makefile that rebuilds exactly what a change affects, headers included, and honors
CCandCFLAGS.- Describe git’s snapshot model: staging, commits, branches, remotes, and hooks.
Processes and exit status
Section titled “Processes and exit status”A process is a running program. It has a numeric id (its PID), a parent process, an environment, and three open files numbered 0, 1, 2. A shell runs a command by creating a child process and waiting for it. When the child ends, it reports an exit status, an integer from 0 to 255 (only the low 8 bits of exit(n) survive, so exit 256 reports 0). CI, make, and Kubernetes all decide by that one number. The shell exposes it and a few other facts as special parameters:
| Symbol | Meaning | Type / shape |
|---|---|---|
$? | exit status of the last command | integer 0 to 255 |
$$ | PID of the current shell (in a script: the script’s own PID) | integer |
$! | PID of the last command started in the background with & | integer |
$1, $2, … | the script’s arguments | strings |
| a signal number: 2 for SIGINT, 9 for SIGKILL, 15 for SIGTERM | integer | |
| the status a shell reports for a child ended by signal | integer |
Every tool in these books follows the same conventions: 0 success; 1 a general failure; 2 wrong usage (bad arguments); 126 found but not executable; 127 command not found; ended by signal , so 130 after Ctrl-C, 137 after SIGKILL (what an out-of-memory kill looks like), 143 after SIGTERM.
Status drives control flow: a && b runs b only if a exited 0; a || b only if it did not. Three settings make scripts fail fast instead of carrying on after an error: set -e (exit when a command fails), set -u (an unset variable is an error), and set -o pipefail (covered with pipes below).
Signals
Section titled “Signals”Exit status is how a process reports its end; signals are how other processes ask for it. A signal is a small asynchronous message the kernel delivers to a process: “stop now”, “you were interrupted”. kill -TERM 4242 sends SIGTERM to PID 4242; Ctrl-C in a terminal sends SIGINT. Each signal has a default action, and for the three that matter here it is “terminate”:
| Signal | Number | Sent by | Can a process catch it? |
|---|---|---|---|
| SIGINT | 2 | Ctrl-C | yes |
| SIGTERM | 15 | kill with no option, Kubernetes, systemd, CI cancellation | yes |
| SIGKILL | 9 | kill -9, the out-of-memory killer, Kubernetes after the grace period | no: the process ends, nothing of it runs |
kill -0 PID sends nothing; it only tells you whether the process exists (status 0) or not. Because SIGKILL cannot be trapped, anything a process cleans up on exit can be left behind, and the next start must detect stale state.
In bash, trap 'commands' TERM replaces the default action with your commands. The rule that surprises everyone: bash runs a trap only after the command it is currently running finishes. While a foreground sleep 30 runs, a SIGTERM waits. The builtin wait, however, returns as soon as a trapped signal arrives. So a script that must stop promptly starts its long waits in the background (sleep 30 &) and then waits for them. Once the trap runs, the background child is still alive; the trap must kill it (jobs -p lists the PIDs of the shell’s background children), or it lives on as an orphan.
Environment
Section titled “Environment”The environment is a list of NAME=value strings each process carries. A child gets a copy of its parent’s environment when it starts, so a child can never change its parent’s variables. In bash, export NAME=value puts a variable into the environment of every later child; NAME=value cmd sets it for one command only. ${NAME:-default} reads a variable and substitutes default when it is unset or empty. Configuration by environment variable is how the system’s services are configured in Kubernetes (TL_* variables), and it is how the worker below finds its state directory.
Files, pipes, redirection
Section titled “Files, pipes, redirection”Every process starts with file descriptors 0 (stdin), 1 (stdout), and 2 (stderr). Programs print results to stdout and diagnostics to stderr, so the two can be separated: cmd > out.txt 2> err.txt; 2>&1 sends stderr wherever stdout goes. A pipe a | b connects a’s stdout to b’s stdin; both run at once. The status of a pipeline is the status of its last command: grep x missing-file | wc -l exits 0 even though grep failed, unless set -o pipefail, which makes the pipeline fail when any part fails.
The C build model and make
Section titled “The C build model and make”With processes covered, the build is the next tool built on them. C is built in two stages. Compiling turns one .c file into one object file: cc -c greet.c -o greet.o. A header (greet.h) declares what another file defines, and #include "greet.h" pastes it into every .c that uses it. Linking combines object files into a program: cc main.o greet.o -o greet. Compiling separately is what makes rebuilds cheap: change greet.c and only greet.o needs compiling again.
make automates exactly that decision. A Makefile is a list of rules:
target: prerequisite1 prerequisite2 recipe line run by the shell (it must start with a TAB character)To build a target, make first brings each prerequisite up to date, then runs the recipe if the target file does not exist or is older than any prerequisite (by modification time). Plain make builds the first target in the file. make only knows the prerequisites you list, headers included. The solution uses these pieces:
| Piece | Meaning |
|---|---|
CC, CFLAGS | variables for the compiler and its flags; make CC=clang overrides them from the command line |
$@, $<, $^ | in a recipe: the target, the first prerequisite, all prerequisites |
%.o: %.c | a pattern rule: how to make any .o from the .c of the same name |
main.o: greet.h | a rule with no recipe: adds a prerequisite to main.o, because make cannot see #include |
.PHONY: clean | clean is a name, not a file; run its recipe every time it is asked for |
The last tool records all of this over time. git records snapshots. A commit is a full snapshot of the tracked files, plus a message, an author, a time, and a pointer to its parent commit, all named by a hash of that content. You choose what goes into the next snapshot by staging: git add file copies the file’s current content into the staging area, and git commit -m "..." turns the staging area into a commit. git status shows what changed and what is staged; git log walks the parents from the newest commit (HEAD); git diff shows unstaged changes. .gitignore lists files git should never offer to track (build outputs like *.o, .venv/).
A branch is a movable name for a commit; a remote is another copy of the repository you git push to. git runs hooks, scripts in a hooks directory, at fixed moments. The CI gate in Software Engineering uses the commit-msg hook, which gets the message file and can reject the commit with a nonzero exit status.
Working it by hand
Section titled “Working it by hand”Before writing either file, work out what they must do.
Who gets rebuilt. The program has three source files. Both .c files include greet.h:
greet <- main.o <- main.c, greet.h <- greet.o <- greet.c, greet.hStarting from a complete build, make rebuilds exactly the targets downstream of the changed file:
| Changed | Recompiled | Relinked | Why |
|---|---|---|---|
| nothing | nothing | no | every target is newer than its prerequisites |
greet.c | greet.o | yes | greet.o is now older than greet.c; greet is then older than greet.o |
main.c | main.o | yes | same, on the other side |
greet.h | main.o and greet.o | yes | both list greet.h as a prerequisite |
greet.h, header rules forgotten | nothing | no | make never learns that the header matters: stale objects |
A worker’s life. Here is a session with the reference worker.sh (state in /tmp/w, a tick every 30 s):
$ WORKER_STATE_DIR=/tmp/w ./worker.sh & # PID 4242readytick$ cat /tmp/w/worker.lock4242$ kill -TERM 4242 # trap runs at once: wait returns early$ wait 4242; echo $?143 # 128 + 15$ ls /tmp/w/worker.lockls: /tmp/w/worker.lock: No such file or directoryThe exit statuses to recognize are 128 + 2 = 130 (SIGINT), 128 + 9 = 137 (SIGKILL; no trap ran, so a lock file stays behind), and 128 + 15 = 143 (SIGTERM). A trap that cleans up and exits 143 after SIGTERM keeps the information that a signal ended the process; a script without a trap is simply killed.
The program. ./greet Ada prints hello, Ada and exits 0; ./greet with no argument prints usage: ./greet NAME on stderr and exits 2.
The requirements
Section titled “The requirements”The C program is given and fixed; the exercise is its build. These three files sit in primers/lang.02/:
#ifndef GREET_H#define GREET_H
#include <stddef.h>
/* Write "hello, <name>" into buf (at most cap bytes, NUL-terminated). Returns the length it wanted to write, as snprintf does. */int greet(char *buf, size_t cap, const char *name);
#endif#include <stdio.h>
#include "greet.h"
int greet(char *buf, size_t cap, const char *name) { return snprintf(buf, cap, "hello, %s", name);}/* primers/lang.02/main.c: exit codes 0 ok, 1 runtime error, 2 usage error */#include <stdio.h>
#include "greet.h"
int main(int argc, char **argv) { char buf[64]; if (argc != 2) { fprintf(stderr, "usage: %s NAME\n", argv[0]); return 2; } int n = greet(buf, sizeof buf, argv[1]); if (n < 0 || (size_t)n >= sizeof buf) { fprintf(stderr, "%s: name too long\n", argv[0]); return 1; } puts(buf); return 0;}The Makefile (primers/lang.02/Makefile) must build greet from main.o and greet.o on plain make, compiling each .c to its own .o and linking with $(CC). It must rebuild only what is downstream of a changed file, as in the table above, headers included. It must compile and link through $(CC), so make CC=clang works. And it must have a clean target that removes greet and the objects, declared .PHONY.
The worker (primers/lang.02/worker.sh, executable, starting with #!/usr/bin/env bash) has four requirements:
- Keep its state in
${WORKER_STATE_DIR:-${TMPDIR:-/tmp}}and tick every${WORKER_INTERVAL:-30}seconds. - On start, if
worker.lockexists in the state directory and the PID in it is alive (kill -0), print why on stderr and exit 1 without touching the lock; if that PID is gone, remove the stale lock and continue. - Write its own PID (
$$) toworker.lock, set its traps, then printreadyas its first line on stdout. - On SIGTERM exit 143, on SIGINT exit 130, in both cases after removing the lock and killing any background child, promptly even while it waits out a 30 s interval.
Building it step by step
Section titled “Building it step by step”Each line of both files follows from a principle above. Try to write each rule and each line of the trap before reading it.
For the Makefile, the reasoning runs in five steps:
- make decides “rebuild or not” by comparing file times. So every rule’s target must be a real file the recipe creates; otherwise the target never exists and its recipe always runs.
- Recompiling only what changed requires one object per source and a separate link step. A pattern rule says this once for every
.c. - make cannot read
#include. Every object that includesgreet.hmust list it, or a header edit changes nothing (the last row of the rebuild table). - The compiler is a choice of whoever runs the build (CI, a sanitizer build). So recipes name
$(CC)and flags are a variable with a default that the caller can override. cleanis an action, not a file; declaring it.PHONYkeeps a stray file of that name from making it “up to date”.
For the worker, five more:
- A lock file proves ownership only if a dead owner can be told apart from a live one. The lock holds a PID, and
kill -0asks the kernel whether that PID exists, so a lock left by a SIGKILL (which no trap survives) is detected and taken over. - A signal must turn into cleanup plus the conventional status 128 + n, so supervisors still see “ended by SIGTERM”. That is a trap per signal calling one cleanup function with the right code.
- A trap runs only between commands. A 30 s foreground
sleepwould postpone it for up to 30 s, past a container’s grace period. Runningsleepin the background and blocking inwaitlets the trap run immediately. - The backgrounded
sleepis a separate process. If the trap exits without killing it, it outlives the script as an orphan, one per restart. - The lock must be in place before anything announces readiness, and the traps must be set before the lock could be left behind by a signal;
readycomes last.
The Makefile
Section titled “The Makefile”CFLAGS ?= -std=c11 -Wall -Wextra -O2 # ?= : a default the caller can override (step 4)OBJS := main.o greet.o
.PHONY: all clean # names, not files (step 5)all: greet # the first target: plain `make` builds greet
# Link: the program depends on every object.greet: $(OBJS) $(CC) $(CFLAGS) -o $@ $(OBJS)
# Compile: one object per source (step 2). Each object also depends on the# header it includes, so editing greet.h rebuilds both (step 3).%.o: %.c $(CC) $(CFLAGS) -c -o $@ $<main.o: greet.hgreet.o: greet.h
clean: rm -f greet $(OBJS)Walk through the rebuild table with it. After a full build, greet is newer than both objects and each object is newer than its .c and greet.h: nothing runs. Touch greet.c: greet.o is older than a prerequisite, so the pattern rule recompiles it ($< is greet.c, $@ is greet.o); now greet is older than greet.o, so it relinks. Touch greet.h: both objects list it, so both recompile, then the link. The recipe-less rules main.o: greet.h only add a prerequisite; the recipe still comes from %.o: %.c. make CC=clang replaces CC everywhere, because no recipe names a compiler. rm -f does not fail when the files are already gone, so make clean twice in a row succeeds.
The worker: configuration and the stale-lock check
Section titled “The worker: configuration and the stale-lock check”#!/usr/bin/env bashset -euo pipefail # fail fast: a failing command, unset variable, or pipe stage
state="${WORKER_STATE_DIR:-${TMPDIR:-/tmp}}" # environment with nested defaultsinterval="${WORKER_INTERVAL:-30}"lock="$state/worker.lock"
# A lock whose PID is gone was left by a process that could not clean up# (SIGKILL, power loss). `kill -0` sends no signal; it only asks "does it exist?".if [ -e "$lock" ]; then old="$(cat "$lock")" if [ -n "$old" ] && kill -0 "$old" 2>/dev/null; then echo "worker: already running (pid $old)" >&2 # diagnostics to stderr exit 1 # and the live owner's lock is left alone fi echo "worker: removing stale lock (pid ${old:-?})" >&2 rm -f "$lock"fiecho "$$" > "$lock" # $$: this script's own PIDkill -0 inside an if condition is exempt from set -e, so “no such process” is a branch, not a crash. -n "$old" guards against an empty lock file, for which kill -0 "" would be an error rather than a no.
The worker: the trap
Section titled “The worker: the trap”stop() { # Kill the background sleep too, or it outlives us as an orphan. `jobs -p` # lists every background child, including one started an instant before # the signal arrived. local kids kids="$(jobs -p)" # shellcheck disable=SC2086 # one word per PID: the splitting is the point if [ -n "$kids" ]; then kill $kids 2>/dev/null || true; fi # the child may already be gone rm -f "$lock" exit "$1" # 128 + n, chosen by the trap (step 7)}trap 'stop 143' TERM # 128 + 15trap 'stop 130' INT # 128 + 2One function, two traps: the cleanup is identical and only the status differs. || true keeps set -e from aborting the cleanup halfway if the sleep exited on its own an instant earlier. The lock is removed before exit, so a supervisor that restarts the worker on exit finds no lock.
The worker: the loop
Section titled “The worker: the loop”echo ready # only now: lock written, traps set (step 10)while true; do echo tick # Sleep in the background and `wait` for it: bash runs a trap only between # commands, and `wait` returns as soon as a trapped signal arrives, while a # foreground `sleep 30` would delay the trap for up to 30 seconds. sleep "$interval" & wait $! || truedoneThe session from the hand example follows line by line: ready and tick are printed; kill -TERM 4242 interrupts wait (step 8), bash runs stop 143, which kills the sleep, removes /tmp/w/worker.lock, and exits 143. When a signal interrupts wait, bash runs the trap, which exits, so the loop never continues. || true covers the other case: a sleep that fails for some other reason (a bad WORKER_INTERVAL), which under set -e would otherwise end the worker with its lock still in place, since there is no trap on plain exit.
The full solution is in Makefile and worker.sh.
Why this design
Section titled “Why this design”In cost, an up-to-date make does one stat per file and runs nothing; a one-file change runs one compile and one link. The worker is idle in wait between ticks and reacts to a signal in milliseconds.
The Makefile uses explicit header rules rather than -MMD -MP dependency files. For two sources and one header they are clearer, and they show what the generated files would contain. A project with many headers should let the compiler generate them (see Further reading).
The worker uses a PID lock with kill -0 rather than flock: it is portable shell and makes the stale-lock problem visible. Its weakness is a race: two workers starting at the same instant can both see no lock and both write one. flock closes that race because the kernel owns the lock and drops it when the process dies. One more tradeoff is accepted: PID reuse. If the dead owner’s PID has been reused by an unrelated process, kill -0 says “alive” and the worker refuses to start. That fails safe (no two owners) but needs a human; a kernel lock avoids it.
What can go wrong
Section titled “What can go wrong”The tests check both artifacts end to end. make must build a greet that prints hello, Ada with status 0 and returns 2 with no argument, the same way a system’s C library is built later. A second make must do no work, for fast edit-build loops. Editing greet.c must rebuild only greet.o and the link, while editing greet.h must rebuild both objects, so there are no stale struct layouts against a shared header such as tinyllm.h. Compile and link must go through $(CC), because sanitizer builds and CI choose the compiler, and clean must work even when a file named clean exists.
For the worker, the script must have an execute bit and a #! line, because entry points are exec’d by CI and by Kubernetes. After ready, worker.lock must hold the worker’s PID. SIGTERM must give status 143 and remove the lock, which is graceful shutdown; SIGINT must give 130 and remove the lock too. With a 30 s interval, SIGTERM must end the worker within 3 s, inside any shutdown grace period. No process of the worker’s group may outlive it. A second start must exit 1 and leave the live owner’s lock alone. And after SIGKILL the lock remains, so the next start must take it over: crash recovery without a human.
The common mistakes, and how the solution avoids each, are collected here.
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
A rule whose target never exists as a file (for example build: producing greet) | every make relinks or recompiles everything | the link rule’s target is the file greet itself; all is .PHONY and only depends on it |
One rule cc main.c greet.c -o greet | every change recompiles every file | the pattern rule %.o: %.c compiles each source to its own object |
No main.o: greet.h and greet.o: greet.h | after a header change the objects are stale and disagree with it | main.o: greet.h and greet.o: greet.h |
A recipe that hardcodes gcc | make CC=clang and sanitizer builds are ignored | every recipe runs $(CC) |
clean not declared .PHONY | a stray file called clean makes make clean do nothing | .PHONY: all clean |
| No trap | the shell dies with the signal (status shown as -15 by Python), the lock stays | trap 'stop 143' TERM; stop removes the lock |
A foreground sleep "$interval" | SIGTERM waits up to 30 s for the sleep to finish | sleep "$interval" & then wait $! |
The trap forgets the background sleep | one orphaned process per restart | stop kills every PID from jobs -p |
| Trusting any existing lock | after one SIGKILL the worker never starts again | the start checks the lock’s PID with kill -0 and removes a stale lock |
| Spaces instead of a TAB before a recipe line | Makefile:9: *** missing separator. Stop. | recipe lines start with a TAB |
Warning: A Makefile that forgets header prerequisites builds cleanly and passes until the day a struct changes. Then old objects link against the new layout with no error at all.
Where this leads
Section titled “Where this leads”The process model returns in nearly every later book. In Software Engineering, The repository and its CI gate treats CI jobs as processes whose exit status is the gate, and its commit-msg hook is a script that rejects with a nonzero status. In Mathematics, the C exercise in Vectors, matrices, row-major layout, and matmul uses a Makefile that builds standalone test binaries from source files and headers; the system’s C runtime extends the same Makefile with a SANITIZE=1 variable to add AddressSanitizer. In AI Engineering, Your first endpoint makes the Rust engine handle SIGTERM: stop accepting, finish in-flight streams, exit. In Systems Engineering, the tracer deploy relies on Kubernetes sending SIGTERM, waiting the grace period (30 s by default), then SIGKILL; status 137 in kubectl describe means SIGKILL. And in Systems Engineering, the first drill reads a crashlooping pod’s exit status and restart count.
The local CI script builds and cleans this primer (make -C primers/lang.02) as a toolchain check, so a broken compiler or make fails at the start. The next section, C, goes deeper into the language this Makefile builds.
Further reading
Section titled “Further reading”- William Shotts, The Linux Command Line, chapters 6, 10, and 24 to 27 (free at linuxcommand.org).
- GNU Make manual, chapters 2 and 4, and “Generating Prerequisites Automatically” for
cc -MMD -MPdependency files; Ninja for a faster scheduler. man 7 signal.- Pro Git, chapters 1 to 3 (free at git-scm.com).
man 1 flock(util-linux), andfcntllocks: the kernel releases the lock when the process dies, so there is no stale lock and no check-then-write race.- krallin/tini
README.md, anddocker run --init: a minimal PID 1 that forwards signals and reaps orphans inside a container. - kubernetes.io, “Pod Lifecycle”, termination of Pods:
preStophooks,terminationGracePeriodSeconds, and readiness removal before SIGTERM.
Key terms
Section titled “Key terms”- exit status: the integer from 0 to 255 a process reports when it ends; 0 means success.
- signal: an asynchronous message from the kernel to a process, such as SIGTERM or SIGKILL.
- trap: a bash handler that replaces a signal’s default action with your commands.
- orphan: a child process that outlives the parent that started it.
- stale lock: a lock file left by a process that died without cleaning up.
- pattern rule: a make rule such as
%.o: %.cthat says how to build any file of one kind from another. - phony target: a make target that names an action rather than a file and always runs.
- commit: a git snapshot of the tracked files plus metadata and a parent pointer, named by its hash.
Summary
Section titled “Summary”- Every process ends with an exit status from 0 to 255; 0 means success, and CI,
make, and Kubernetes all decide by that one number. - means “ended by signal ”: 130 after SIGINT, 137 after SIGKILL, 143 after SIGTERM. A trap that cleans up and exits 143 keeps that information.
- Bash runs a trap only between commands, so sleep in the background and
wait, or a 30 ssleepdelays shutdown by up to 30 s. - SIGKILL cannot be trapped, so the next start must detect stale state, here with
kill -0on the lock’s PID. - make rebuilds a target when a prerequisite is newer, and it only knows the prerequisites you list, headers included.
Review questions
Section titled “Review questions”-
Why is there an
alltarget instead of makinggreetthe first rule?Answer
Either works for plain
make, which builds the first target.allgives a stable name for “build everything” that stays correct if more programs are added, and declaring it.PHONYmeans its own up-to-date state never matters: onlygreet’s does. -
What does
makedo aftertouch greet.h, and which lines of the Makefile cause it?Answer
It recompiles
main.oandgreet.oand relinksgreet.main.o: greet.handgreet.o: greet.hmake both objects older than a prerequisite; the pattern rule supplies their recipe; thengreet: $(OBJS)is older than its objects. -
The worker is killed with SIGKILL. What is left behind, and how does the next start cope?
Answer
No trap runs, so
worker.lockstays with the dead PID, and the backgroundedsleepmay live on until it finishes its interval. The next start reads the PID,kill -0fails, so it removes the stale lock and takes over. -
Why is
sleeprun in the background and then waited for, rather than in the foreground?Answer
bash runs a trap only after the current foreground command finishes, so a SIGTERM during
sleep 30would be handled up to 30 s later. The builtinwaitreturns as soon as a trapped signal arrives, so the trap runs at once. -
Why exit 143 instead of 0 after a clean SIGTERM shutdown?
Answer
128 + 15 tells whoever waits on the process that it ended because of SIGTERM, which is the convention shells and supervisors use. Exiting 0 would claim the work finished on its own, hiding that it was stopped.