Processes and the system-call API: fork, exec, signals, file descriptors

How a program becomes a process, how it asks the kernel for anything, and how processes are created, replaced, signalled, wired together and reaped, with the kernel source (Linux v6.12) where it explains something and real runs on a Linux 5.10 kernel. The running example is the training job of Topic: operating-systems. Data as of October 2026. Reading: 50 min, plus 19 in closed details.

The idea in one screen

A process is a record the kernel keeps for a running program (its memory, its descriptor table, its signal state, its identity), and the program can change that record only by asking through a system call: fork copies the record, exec replaces the program inside it, wait collects its end, a signal interrupts it, and descriptors are its handles on files, pipes and sockets.

Fig. 1, step by step: the job is a tree of records the kernel owns; every arrow into the kernel is one system call

  1. Four processes in user space. The running job of the root page, as recorded from inside its container while it trained (section 1): PID 1 is the container's shell, its child python (PID 13) is the trainer, and the two DataLoader worker processes pt_data_worker (PIDs 27 and 29) are the trainer's children, made by fork. Under torchrun the tree has one more level: torchrun (the launcher, "elastic agent": starts, watches and stops the trainers) starts one python train.py per GPU (each in its own session, --nproc-per-node of them), each with its own workers (made by fork, spawn or forkserver).
  2. Each process is a record below the plate. The glass plate is user space; underneath is kernel memory the program cannot touch. The trainer's 8 threads (OpenMP/ATen workers, the pin_memory thread, NCCL threads on a GPU node: same process) are 8 tasks, one task_struct each, with one thread group id, sharing one address space (mm), one descriptor table (files) and one handler table (sighand). Each worker has 4.
  3. One door: the system call. Whatever the trainer needs from the kernel (read a batch, fork a worker, wait for it, send a signal) goes down through one trapping instruction and comes back as a number: about 270 ns for the cheapest call (269 ns for getppid measured here, section 2).
  4. fork made the workers. Each worker's record is a copy of the trainer's: its own address space (pages shared copy-on-write until written, section 3) and its own descriptor table, whose entries point at the same pipes: fds 4 to 8 are the same in the trainer and the worker (section 7).
  5. Signals arrive from outside. A signal is recorded in a record and acted on when the thread next returns to user mode (section 6): SIGTERM from docker stop reaches train.py's handler, SIGCHLD from a dying worker reaches the DataLoader's. exec (section 4) would replace the program inside a record and keep the record.

You need: user mode, kernel mode and the running job from the root's section 1. This page owns the process API; what it touches is owned elsewhere and linked: page tables and copy-on-write (Virtual memory), running on a CPU (Scheduling and CPU time), locks and event loops (Concurrency), namespaces and cgroups (Containers and isolation).

Task, TGID
Linux's record per thread; a process is the tasks sharing one thread group id, which getpid() returns.
System call
a numbered request to the kernel through one trapping instruction; failure comes back as a negative number that becomes errno.
Copy-on-write
fork shares the parent's pages read-only and copies a page only when one side writes it.
Zombie, orphan, subreaper
an exited process not yet waited for; a process whose parent died; the ancestor that adopts orphans instead of PID 1.
Pending, blocked
a signal recorded but not yet acted on; a signal held back by the thread's mask.
Descriptor, description
the small integer in one process's table; the kernel object it points to, which holds the file offset.
Close-on-exec
a per-descriptor flag: exec closes it, so the new program does not inherit it.
Process group, session
sets of processes signalled together (Ctrl-C, killpg); a session is what setsid starts.
The calls in one table: what each does, its measured cost, where it bites (summary of the sections below)
CallWhat it doesCost measured hereWhere it bites in ML workSee it with
read, any syscallEnter the kernel through one instruction, get a number back (or -1 and errno)about 270 ns for the cheapest call; about 124 µs each under straceMillions of tiny reads in a data loader; profiling with strace distorts timings 460-foldstrace -c -f, perf trace
forkCopy the calling process (memory shared copy-on-write, page tables copied)0.25 ms empty; 17 ms with 1 GiB in 4 KiB pages; flat with huge pagesDataLoader workers under the fork start method; fork after CUDA or threadsstrace -e clone, /proc/<pid>/status VmPTE
posix_spawn, vforkStart a new program without copying the parent's page tablesabout 0.39 ms, whatever the parent's sizesubprocess from a big trainer (Python already uses it)strace -e clone,clone3,execve
execveReplace the program in this process; keep PID and non-CLOEXEC descriptorspart of spawn: a fresh Python with torch is about 0.9 sspawn and forkserver workers re-import torchstrace -e execve
wait4, exitCollect a child's exit status; until then it is a zombiea zombie costs a PID and a little kernel memoryZombie workers when the script is PID 1 in a containerps -o stat (Z)
kill, rt_sigactionSend a signal; choose what it does on arrivalPython handler runs 0.2 ms after kill, or only after a long C++ call returns (1.2 s measured)Graceful preemption: SIGTERM, 30 s, SIGKILL/proc/<pid>/status SigCgt
pipe, dup2, closeMake and rewire descriptors; a pipe holds 64 KiBa leaked write end delayed EOF by 2.0 s (until the leaker exited)Hangs waiting for EOF; "Too many open files" with tensor sharingls -l /proc/<pid>/fd, lsof

Measured on Docker Desktop's Linux VM (kernel 5.10.104, arm64, Apple M1 Pro), 2026-10-05, inside the root page's lab image (Debian 12, glibc 2.36, Python 3.11.2, torch 2.14.1+cpu); scripts and raw outputs in this page's src/runs/. Each number is explained, with its spread, in the section that owns it. What transfers to an x86-64 GPU server: the mechanisms and the ratios; the absolute nanoseconds differ by CPU and kernel.

1. The process, as the kernel sees it

ch. 4 The Abstraction: The Process

A program is a file: instructions and initial data. Running it needs memory to hold it, a CPU pointed at its first instruction, a record of every file it opens, and a way to stop, resume and clean up after it. OSTEP calls the bundle a process's machine state: its memory (the address space), its registers (including the program counter and stack pointer), and its I/O state (open files). In Linux the record is struct task_struct (include/linux/sched.h line 778), several kilobytes, and the surprise for most people is that there is one per thread, not one per process. Linux calls each a task; a "process" is a group of tasks that point at the same memory, the same file table and the same signal handlers (the bottom row of the figure above).

PID and TGID. Every thread has its own id, stored in pid. What user space calls the process id is the thread group id tgid, the id of the first thread. getpid() returns the tgid; gettid() (Python's threading.get_native_id()) returns the task's own id. top -H and /proc/<pid>/task/ show the threads one by one.

The task_struct fields this page uses, with their v6.12 lines (reference)
Field (v6.12 line)What it holdsShared by threads?Section
__state (786)Running, sleeping, stopped...; the letter ps showsno, per taskbelow
mm (921)The address space: page tables and mappingsyes3, and the virtual memory page
exit_state, exit_code (925 to 926)Zombie or dead; the status the parent will collectno5
pid, tgid (1018 to 1019)This task's id; the id of its thread grouptgid yesbelow
real_parent, children (1032, 1040)The process treeper task5
cred (1114)User and group ids, capabilitiesusually8
comm (1128)The 15-character name ps shows (pt_data_worker)no9
fs, files (1141, 1144)Current directory and root; the file descriptor tableyes7
nsproxy (1151)Namespaces: which PIDs, mounts, network it seesyescontainers page
signal, sighand, blocked, pending (1154 to 1160)Process-wide signal state, the handler table, this thread's mask and private pending setsignal and sighand yes; blocked and pending no6
thread (1602)The CPU registers saved while the task is not runningnoscheduling page

The running job, read from /proc

The job with two fork DataLoader workers, captured from inside its container while it trained (src/runs/in_container_proc.sh). /proc is not on any disk: the kernel writes this text when you read it (proc(5)).


Main process: /proc/<main>/status (selected lines)
A DataLoader worker

Tgid equals Pid for both: they lead their thread groups. The main process has 8 threads (the root's Syscall tracer tab shows the clone calls that create them); each worker has 4 even though DataLoader sets torch.set_num_threads(1) inside it, because a forked child inherits only the thread that called fork and starts new ones as it imports and computes. The worker's PPid is the main process; the main process's PPid is 1, the container's shell. SigIgn and SigCgt are bit masks of ignored and caught signals (decoded in section 6: torch caught different signals in the worker than in the main process). Seccomp: 2 means a seccomp filter is active (Docker's default profile); the ctxt_switches counters are how often this task gave up the CPU voluntarily (blocking) or was preempted.

Process states

The one-letter state comes from a table in fs/proc/array.c line 126:

LetterKernel nameMeaningWhere you meet it in training
RrunningOn a CPU or ready to run (OSTEP separates running from ready; Linux shows both as R)The training loop computing; a busy worker
SsleepingWaiting for an event; a signal can wake it (interruptible)Workers waiting on their index queue; main waiting for a batch
Ddisk sleepWaiting inside the kernel, uninterruptible: not even SIGKILL acts until the wait endsPage faults on a slow network file system; a hung NFS or Lustre mount (the root's Debug lab case "Slow storage: workers sleep in D state on page faults")
T, tstopped, tracing stopStopped by SIGSTOP or Ctrl-Z; stopped by a debugger or straceA job paused by kill -STOP; every system call under strace
ZzombieExited; its parent has not collected the status yetSection 5
XdeadBeing removed; you will almost never see it
IidleA kernel thread with nothing to do (not counted in the load average)Hundreds of them in ps on any host

A lowercase s, l or + after the letter in ps means session leader, multi-threaded, and in the foreground process group (section 8). So Sl is "sleeping, has threads": exactly the workers above. How a task is chosen to run, and what is saved when it stops, is Scheduling and CPU time.

2. System calls: the one door into the kernel

ch. 6 Limited Direct Execution

Your program runs directly on the CPU at full speed, but in user mode, where the hardware refuses anything that could harm other programs: touching a device, changing the memory map, disabling interrupts. The kernel runs in kernel mode. A program that wants something privileged must ask, and the request has to be a controlled jump into kernel code at a place the kernel chose, never at an address the program picks. That jump is a system call (the root's section 1 introduced it; here is exactly how it works).

The contract: a number, six registers, one instruction. The program puts the call number and up to six arguments in fixed registers and executes one trapping instruction; the kernel puts the result back in a register. That convention is the system-call ABI (application binary interface): on arm64 (this page's runs) the number goes in x8, the arguments in x0 to x5, the instruction is svc #0 ("supervisor call") and read is number 63; on x86-64 (most GPU servers) they are rax, rdi, rsi, rdx, r10, r8, r9, syscall and number 0. Failure is a number too: a negative result between -4095 and -1, which glibc turns into errno and -1 (the EBADF mode of Fig. 2). Step through one call, then switch to the error and the strace paths:

Fig. 2, step by step: one os.read(fd, 4096), real instructions and kernel functions

  1. Python asks for up to 4,096 bytes. data = os.read(fd, 4096) with fd = 3, an open 27-byte file. The bytecode loop calls the C function behind os.read; os_read_impl allocates a 4,096-byte bytes object and releases the GIL, so other Python threads can run while this one waits in the kernel.
  2. glibc's read(3, buf, 4096). The C calling convention already put the arguments in x0, x1 and x2, exactly where the system-call ABI wants them. __libc_single_threaded is 0 because torch started threads, so glibc takes the cancellable path (this call is a cancellation point).
  3. mov x8, #63, then svc #0: user mode ends. The call number goes in x8 (63 is read in the generic table arm64 uses). The CPU raises a synchronous exception: it saves the return address in ELR_EL1 and the status in SPSR_EL1, switches to EL1 (kernel mode) and its stack, and jumps to the kernel's vector. The program cannot choose where it lands. Mode switch 1.
  4. Kernel entry: what kind of exception? All registers are saved into struct pt_regs on the kernel stack. el0t_64_sync_handler reads the exception class, SVC64, a system call; el0_svc calls do_el0_svc with regs[8] = 63.
  5. sys_read: find the file, copy the bytes. invoke_syscall indexes sys_call_table[63] (bounds-checked with array_index_nospec) and calls sys_read. It looks up fd 3 in this process's descriptor table (section 7), gets the struct file, and vfs_read copies 27 bytes from the page cache into buf.
  6. Result in x0, eret back to user mode. The kernel writes 27 into the saved x0 and executes eret: EL0 again, at the instruction after svc. Mode switch 2.
  7. glibc: is it an error? cmn x0, #0x1, lsl #12 compares 27 with -4096. Not in -4095..-1, so it is a byte count, and glibc returns 27.
  8. data is 27 bytes. CPython takes the GIL back and resizes the bytes object from 4,096 to 27 bytes. Two mode switches in total; without a tracer the whole trip costs a few hundred nanoseconds (269 ns for getppid, measured).

Register values for the open case are the ones a 27-byte hello.txt gives (the root's language-to-kernel experiment); addresses are shown symbolically. Under strace the tracee stops twice per call (entry and exit) and the tracer runs in between, which is where the 460-fold slowdown measured below comes from.

The two ABIs side by side, and why strace shows clone for fork (reference)
arm64 (this page's runs, Graviton, Grace)x86-64 (most GPU servers)
Instructionsvc #0 ("supervisor call")syscall
Call number inx8rax
Arguments inx0 to x5rdi, rsi, rdx, r10, r8, r9
Result inx0rax (the CPU also overwrites rcx and r11)
Number of read63 (unistd.h line 172)0 (syscall_64.tbl)
A fork system call?none: the generic table has only clone (220), so glibc's fork() calls cloneyes (57), but glibc's fork() calls clone anyway

Registers and instructions: syscall(2), "Architecture calling conventions". glibc 2.36 makes fork a clone with CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID | SIGCHLD (arch-fork.h line 37), which is why every strace of a fork, including the root's Syscall tracer tab, shows clone.

glibc's real read(), disassembled: the fast path, the door and errno (depth)

The wrapper you actually call. Nobody writes svc by hand. The C library (glibc) has one small function per system call. Here is glibc's real read() on this page's machine, disassembled with gdb, with the lines that matter:


Four things to notice. (1) The single-threaded fast path: glibc checks __libc_single_threaded (gdb names the variable) and, if other threads exist, takes a second path that wraps the same svc in calls that make read a thread cancellation point (SYSCALL_CANCEL in sysdep.h line 118; read.c line 26). After import torch your process is multi-threaded, so it always takes the slower path. (2) mov x8, #63, then svc #0: the door. (3) cmn x0, #0x1, lsl #12 compares the result with -4096: the kernel reports failure by returning a negative error number between -4095 and -1, never by setting a variable. (4) On failure the wrapper negates it, stores it in errno (a per-thread variable, reached through the thread pointer register tpidr_el0) and returns -1. CPython then turns -1 plus errno into an exception: errno 9 (EBADF) becomes OSError: [Errno 9] Bad file descriptor, errno 2 becomes FileNotFoundError.

Inside the kernel, function by function at v6.12 (depth)

On arm64, svc raises a synchronous exception: the CPU switches to EL1 (kernel mode), saves the return address and status, and jumps to the exception vector the kernel installed at boot. From there it is ordinary C, at a pinned version (Linux v6.12):

  1. el0t_64_sync_handler reads the exception class; ESR_ELx_EC_SVC64 (line 729) means "a system call".
  2. el0_svc calls do_el0_svc, which passes regs->regs[8], your x8, as the call number.
  3. el0_svc_common handles tracing (this is where strace and seccomp hook in), then invoke_syscall looks the number up in sys_call_table with array_index_nospec (line 48), a bounds check that a speculating CPU cannot skip (a Spectre defence), and calls the function, here sys_read.
  4. The return value is stored back into the saved x0, and eret drops the CPU back to EL0 at the instruction after svc.

x86-64 is the same shape: syscall jumps to entry_SYSCALL_64, which calls do_syscall_64.

What a crossing costs

The root measured the ladder on this machine: a function call about 1.3 ns, clock_gettime about 24 ns because the vDSO serves it without entering the kernel (vdso(7)), the cheapest real call (getppid) about 281 ns, a 1-byte read about 316 ns. This page's own getppid loop: 269 ns per call through glibc, about the same from Python's os.getppid() (250 ns, best of 5 against a median of 5: the kernel crossing dominates), and 124 µs per call under strace, about 460 times slower.

Why strace is so slow, and what to use instead
strace uses ptrace(2): at every system call entry and exit the kernel stops your thread and wakes strace, which reads your registers with more system calls, prints, and resumes you. Counts and order from strace are exact; durations are not (the root's job ran about 170 s under strace against about 2 s without). For timing use perf trace or perf stat -e 'syscalls:sys_enter_*' (kernel tracepoints, no stops), or strace --seccomp-bpf -e trace=..., which uses a seccomp filter so the tracee stops only on the calls you asked for.
The bill, measured by tracing the tracer; PEP 475 word for word (depth)

PEP 475: "System call wrappers provided in the standard library should be retried automatically when they fail with EINTR", and "the system call is only retried if the signal handler does not raise an exception".

For each extra call traced, strace itself made 4 wait4, 4 ptrace and 2 write calls (the difference between tracing 5,000 and 10,000 getppid calls, src/runs/out/strace_meta.txt), plus two stops of your thread, each a round trip through the scheduler.

Predict: a data loader makes 2 million small read calls per epoch and takes 10 s. You run it under strace -f to find out why. About how long will the epoch take?

A crossing costs hundreds of nanoseconds; under strace, a hundred microseconds

Interrupted calls: EINTR and restarting

A call that blocks (a read from an empty pipe, a wait, a sleep) can be interrupted by a signal whose handler runs (section 6). The kernel then restarts the call after the handler returns, if the handler was installed with SA_RESTART and the call is restartable, or fails it with EINTR ("interrupted system call") and leaves the retry to you (signal(7), "Interruption of system calls"). C code that forgets this has a bug that shows only when a signal arrives, for example on preemption. Python retries for you since 3.5, unless the handler raises (PEP 475); that is why time.sleep keeps sleeping after its handler ran in section 6. The root's Syscall tracer tab lists every call the job makes; seccomp, the filter that decides which numbers a container may call, is Containers and isolation.

3. Creating processes: fork, threads, vfork, posix_spawn

ch. 5 Interlude: Process API

A new process needs everything a process has: an address space, a descriptor table, signal settings, an identity. Unix's answer, from 1970 and still the default, is to copy the caller with fork(): one call, two returns. The copy is then free to change itself (redirect its output, drop privileges) and, usually, to replace its program with exec (section 4).

pid_t pid = fork();          /* one call, two returns */
if (pid == 0) {               /* in the child: fork returned 0 */
    execlp("python", "python", "train.py", NULL);   /* only returns on failure */
    _exit(127);
}
int status; waitpid(pid, &status, 0);   /* in the parent: pid is the child's PID */

Threads and processes are the same call with different flags

Every way of making a task ends in one kernel function, copy_process in kernel/fork.c. It allocates a new task_struct and then, for each resource, either shares the parent's or copies it, decided by clone flags. Plain fork passes none of the sharing flags, so everything is copied; a thread passes all of them; vfork shares only the memory.

Fig. 3, step by step: what fork, a thread and vfork do to the parent's memory

  1. The parent holds 1 GiB. A C program that has written to 1 GiB of ordinary memory in 4 KiB pages: 262,144 pages, described by page tables that grew from 48 KiB to 2,100 KiB (the parent's VmPTE, this page's run). The 16 cubes stand for the pages.
  2. fork(): a new task and a copy of the page tables. With no sharing flags, copy_mm copies every mapping and the page tables of private memory, but not the pages: both tables point at the same pages, now marked read-only. The descriptor table is copied the same way: new entries, the same open files. os.fork() is a clone with no sharing flags.
  3. A write copies one page. When either side writes a shared page, the CPU faults, the kernel copies that one page and points the writer's entry at the copy: copy-on-write. Pages nobody writes stay shared forever; what this does to a DataLoader worker's memory is Virtual memory.
  4. A thread copies nothing. pthread_create (a Python thread too) is a clone with CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD and more: the new task joins the caller's thread group (so getpid() returns the same number) and points at the same page tables, descriptor table and handlers. That is why a thread is cheap, and why one thread's crash takes the process down.
  5. vfork and posix_spawn borrow, then exec. CLONE_VM|CLONE_VFORK: the child runs on the parent's memory (nothing to copy, so the cost does not grow with the parent) and the parent is suspended until the child calls exec or _exit. subprocess in Python 3.11 starts children this way.
The copy function and flag for each resource (v6.12) (reference)
ResourceCopy function (v6.12)Shared if this flag is setPlain fork (no flags)
Address spacecopy_mm then dup_mm and dup_mmapCLONE_VMCopied: every mapping, and the page tables of private memory, with writable pages marked read-only so the first write copies the page (copy-on-write)
Descriptor tablecopy_files then dup_fdCLONE_FILESCopied table; the entries point to the same open files (section 7)
Current directory, root, umaskcopy_fsCLONE_FSCopied
Signal handlerscopy_sighandCLONE_SIGHANDCopied: same handlers, same ignored set
Thread group(the tgid)CLONE_THREADNew group: a new process

Only the thread that called fork exists in the child, and pending signals, timers and locks are not inherited (details below). The flags in Fig. 3 were recorded with strace in this page's runs (src/runs/out/clone_flags.txt).

What the child does not inherit, the flag combinations the kernel refuses, and the strace lines (depth and raw output)

The kernel refuses inconsistent combinations: CLONE_THREAD without CLONE_SIGHAND, and CLONE_SIGHAND without CLONE_VM (fork.c lines 2145 and 2153). The child also does not inherit its parent's PID, pending signals, timers, record locks, memory locks (mlock), or resource counters, which copy_mm resets to zero (page-fault and context-switch counts, line 1701; the full list is in fork(2)). And only the thread that called fork exists in the child.

CLONE_VFORK in the first line is subprocess: Python 3.11's subprocess starts children with vfork semantics (_USE_VFORK = True in Lib/subprocess.py); it uses posix_spawn only when close_fds=False and a few other conditions hold (lines 1774 to 1779 in the same file).

Threads as a programming model (locks, the GIL, futexes) are Concurrency; within a process they share memory cheaply and crash together, and each process has its own GIL in CPython.

vfork and posix_spawn: start a program without copying the parent

If the child is going to call exec straight away, copying the parent's page tables is wasted work. vfork (clone with CLONE_VM | CLONE_VFORK) lets the child borrow the parent's memory and suspends the parent until the child calls exec or _exit (the kernel waits in wait_for_vfork_done). It is fast and dangerous: the child must not return from the function that called vfork or touch the parent's variables, because it is running on the parent's memory. posix_spawn wraps that danger in a safe API: glibc 2.36 implements it with CLONE_VM | CLONE_VFORK on a separate stack (spawni.c line 385), and lets you list the descriptor and signal changes to apply in the child.

Predict: a C program holds 1 GiB of memory it has written to (ordinary 4 KiB pages). It runs fork(), and the child exits immediately. How long does fork plus wait take, compared with the same program holding no memory (0.25 ms)?

Anything built on fork scales with the parent's memory; vfork and posix_spawn do not. A trainer with tens of gigabytes resident that shells out (os.system, a fork-based multiprocessing child, a monitoring script started with fork) pays milliseconds to tens of milliseconds per child, and the copy-on-write faults afterwards on top. Python's own subprocess is already on the fast path.

Fork grows with the parent's page tables; vfork and posix_spawn stay flat measured, median of 41

Parent with 0 to 1,024 MiB of touched anonymous memory in 4 KiB pages; time from the call to waitpid returning, so it includes the child's start and exit. fork_exit: fork, child _exit. fork_exec: fork, child execve("/bin/true"), what a shell does. vfork_exit and spawn_exec (posix_spawn of /bin/true) borrow the parent's memory. Source src/runs/c/spawn_cost.c, one CPU, kernel 5.10; bars show the median, whiskers the 10th to 90th percentile.

The same question from Python, with torch loaded

First, os.fork() from a process that imported torch costs about 6 ms even with no big arrays, and subprocess.run stays under 1 ms because of vfork. Second, adding 1 GiB of NumPy did not slow fork down at all, because NumPy asked the kernel for transparent huge pages on that array (AnonHugePages 1,022 MiB): one page-table entry covers 2 MiB instead of 4 KiB, so there are 512 times fewer entries to copy. With NUMPY_MADVISE_HUGEPAGE=0 (NumPy's switch, numpy docs) the same fork took 22.5 ms. This VM's THP setting is madvise, so only memory that asks for huge pages gets them; PyTorch's CPU tensors use a different allocator (Memory allocators). Third, a spawn or forkserver child is a fresh interpreter that imports torch again, about 0.65 to 0.94 s here, matching the root's 0.836 s and 0.763 s to the first batch.

From Python with torch loaded: subprocess stays under 1 ms; huge pages make fork of 1 GiB cheap

Fork in a multi-threaded process

Only the calling thread survives fork, but all of memory is copied, including every lock. If another thread held a lock at that instant (the allocator's, a logging handler's, an OpenMP runtime's), the child has a lock that no thread will ever release, and the first time the child needs it, it hangs forever. POSIX says that after fork in a multi-threaded process the child may only call async-signal-safe functions until it calls exec (fork(2), NOTES). pthread_atfork handlers let libraries reset their locks around fork, and CPython does this for its own locks, but not every library does. Python 3.12 started warning: "if Python is able to detect that your process has multiple threads, os.fork() now raises a DeprecationWarning" (os.fork docs), and Python 3.14 moved the Linux default start method to forkserver for this reason. The root's Debug lab reproduces the hang ("A worker hangs forever: fork while another thread holds a lock"), and the root covers fork after CUDA. What happens to the pages after fork (copy-on-write faults, the reference-count problem that makes DataLoader workers grow) is Virtual memory and the root's OS simulators tab.

4. exec: replacing the program, keeping the process

ch. 5 Interlude: Process API

fork gives you a second copy of the same program. To run a different one, the process throws away its code and memory and loads a new program, while staying the same process: same PID, same parent, same place in the tree. That is execve(path, argv, envp), the one system call behind execl, execvp, os.execv and every shell command. On success it never returns, because the code that called it no longer exists. The point of no return is begin_new_exec: it drops the old address space, kills the process's other threads, closes every descriptor marked close-on-exec, and resets every caught signal to its default action, because the handler functions lived in the memory that was just discarded.

Fig. 4, step by step: the recorded run, before and after execve

  1. Before: PID 17 runs exec_keep. It opened fd 5 without O_CLOEXEC and fd 6 with it, installed a handler for SIGUSR1 (the handler is an address in its own code), ignored SIGUSR2 and blocked SIGHUP.
  2. execve drops the old address space. begin_new_exec is the point of no return: the old code, heap and stack are gone, and so is any way back to the call.
  3. The new program is mapped. The kernel maps showself and its dynamic loader, which maps libc, and starts it on a fresh stack. The process's other threads were killed on the way.
  4. Close-on-exec descriptors close; the others stay. fd 6 is closed; fds 0, 1, 2 and 5 survive with the same open files and offsets.
  5. Caught signals reset; ignored and blocked stay. The handler for SIGUSR1 lived in the memory that was just discarded, so SIGUSR1 is back to its default action (SigCgt 0). SIGUSR2 is still ignored (SigIgn 0x800, signal 12) and SIGHUP still blocked (SigBlk 0x1, signal 1).
  6. Same process, new program. PID 17 before and after, same parent; showself prints open fds: 0 1 2 5.
What the kernel does, step by step: binary formats, #! scripts, the dynamic loader (depth)
  1. do_execveat_common opens the file and builds a linux_binprm, the description of the program to load; bprm_execve checks permissions and asks each binary format handler whether it recognises the first bytes.
  2. An ELF executable (the format of compiled programs on Linux) is mapped by binfmt_elf; a file starting with #! is a script, handled by binfmt_script, which restarts exec with the interpreter named on that line and the script as an argument. That is how ./train.py with #!/usr/bin/env python3 runs.
  3. begin_new_exec is the point of no return. It drops the old address space and installs a new one, kills other threads of the process, closes every descriptor marked close-on-exec (do_close_on_exec, line 1318), and resets every caught signal to its default action (flush_signal_handlers, line 1355): the handler functions lived in the memory that was just discarded.
  4. For a dynamically linked program, the kernel maps the program and its dynamic loader (ld-linux-aarch64.so.1 here) and jumps to the loader, which maps libc and every shared library and then calls the program's entry point. The root's Syscall tracer tab shows this storm of openat and mmap calls for import torch.

What survives exec: measured

Before exec, the test program opened fd 5 without O_CLOEXEC and fd 6 with it, installed a handler for SIGUSR1, ignored SIGUSR2, and blocked SIGHUP. Then it exec'd a small program that only prints its own state (src/runs/c/exec_keep.c, showself.c):


StateAfter execveSeen above as
PID, parent, process group, sessionkeptsame pid before and after
Descriptors without close-on-execkept, same offsetsfd 5 still open
Descriptors with O_CLOEXECclosedfd 6 gone
Caught signals (handlers)reset to defaultSigCgt all zero
Ignored signalsstay ignoredSigIgn 0x800 = signal 12, SIGUSR2
Blocked signals (the mask)keptSigBlk 0x1 = signal 1, SIGHUP
Memory, threads, atexit handlers, stdio buffersgone
Environment, argvwhatever you pass to execve
Current directory, umask, rlimits, user ids (unless set-user-ID)kept

Two rows cause real bugs. Ignored stays ignored: a launcher that ignores SIGTERM or SIGINT (or a non-interactive shell that starts a job in the background, which by POSIX sets SIGINT and SIGQUIT to ignored, visible in the job's SigIgn decoded in section 6) passes that on to everything it execs, and a program that never installs its own handler cannot be stopped with that signal. Blocked stays blocked: a signal blocked by a parent is still blocked in the new program, and a pending one waits. Python's subprocess undoes only its own part: with the default restore_signals=True it resets the signals CPython itself ignores ("Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals", subprocess docs); anything else a launcher ignored or blocked reaches the child unchanged.

The trap in the first version of this experiment (provenance)

The first version of this experiment exec'd /bin/sh to print its state and saw an empty mask and two caught signals: Debian's dash clears the mask and installs its own handlers when it starts. Measuring what a mechanism does through a program that changes the thing you measure is a classic trap; the version above uses a program that changes nothing.

Why fork and exec are separate
Splitting "make a process" from "run a program" means the child can set itself up with ordinary calls in between: dup2 a log file onto fd 1, chdir, setsid, drop privileges, set rlimits, close descriptors. No special API needed. OSTEP's chapter 5 makes this argument, and it is why a shell can implement python train.py > log 2>&1 & in a few lines (step through it in section 7). The cost is the fork itself (section 3), which is why posix_spawn takes those set-up steps as a list of "file actions" instead. How a program's file is mapped into memory is Virtual memory.

5. wait, exit, zombies, orphans and PID 1

ch. 5 Interlude: Process API

When a process ends, someone usually needs to know how: did the worker finish, crash, or get killed? The kernel keeps the answer until the parent asks for it. Between "ended" and "asked" the process is a zombie; a process whose parent ends first is an orphan and needs a new parent. Containers make PID 1 your problem.

Three ways to end

CallWhat it doesUse it
exit(n) (C), sys.exit(n) (Python)Runs atexit handlers, flushes stdio buffers (Python also runs finally blocks and finalizers), then the system call exit_groupNormal end of a program
_exit(n), os._exit(n)The system call exit_group directly: all threads end now; nothing in user space runsIn a forked child that must not run the parent's cleanup
the exit system callEnds one thread; what a returning thread function becomesNever directly

Why _exit in a child matters: after fork the child has a copy of everything the parent buffered but has not written yet. If both call exit, both flush, and the text is written twice. Measured with stdout going to a file (src/runs/c/fdshare.c):

Predict: printf("buffered line from pid %d ", getpid()); with no newline, then fork(); the child prints "(child)\n" and calls exit, the parent prints "(parent)\n" and returns. stdout is a file. How many times does "buffered line" appear in the file?

Exit status, and where 137 and 143 come from

wait4 (or waitpid, waitid) gives the parent a status word. WIFEXITED(s) and WEXITSTATUS(s) say it exited and with which number (0 to 255); WIFSIGNALED(s) and WTERMSIG(s) say a signal killed it (wait(2)). Shells, Docker and Kubernetes fold the two into one number: an exit code below 128 is the program's own; 128 + n means "killed by signal n".

CodeMeansTypical training cause
0exited normallyfinished, or caught SIGTERM and checkpointed
1exited with 1an uncaught Python exception; torchrun after a worker failure or a death signal
137 = 128 + 9SIGKILLthe OOM killer, or the grace period ran out after SIGTERM
143 = 128 + 15SIGTERM, default actionstopped with no handler installed
139 = 128 + 11, 135 = 128 + 7SIGSEGV, SIGBUSa crash in native code; a full /dev/shm in a DataLoader worker

Python's subprocess reports a signal death as a negative returncode (-9, -15) instead.

Zombies: ended, not yet collected

When a process exits, the kernel frees its memory and descriptors but keeps its task_struct, its PID and its exit status, and sends SIGCHLD to the parent. The entry stays until the parent waits (wait_task_zombie releases it). Measured (src/runs/c/lifecycle.c): the exited child shows state Z with its parent's PID until waitpid returns its status (WEXITSTATUS 7), and then /proc/<pid> is gone; an orphaned grandchild's getppid() becomes 1, or the subreaper's PID when the parent marked itself one.

The zombie, before and after wait (raw output)

A zombie costs no CPU and almost no memory, but it holds a PID, and PIDs are limited: per container by the cgroup's pids.max, which counts threads too (the root's Debug lab case "BlockingIOError on fork: the pids limit counts threads too"). A parent that never waits, in a long run that starts many short-lived children, eventually cannot fork.

Orphans: who adopts a child whose parent died

When a process exits, forget_original_parent gives each of its children a new parent chosen by find_new_reaper: the nearest ancestor that marked itself a subreaper with prctl(PR_SET_CHILD_SUBREAPER), otherwise PID 1 of the PID namespace. Only the direct children move; grandchildren keep their own parents. Measured with a chain me, b, c, d in which b exits:

Reparenting to PID 1, to a subreaper, and the chain (raw output)

c (pid 14) moved to PID 1, while d (pid 15) stayed c's child. OSTEP's homework simulator fork.py by default moves every descendant of an exiting process to the root, a simplification; its -R flag moves orphans to their grandparent instead. Run Linux's rule and OSTEP's on the same actions:

A zombie stays until its parent waits; orphans move to the nearest subreaper or PID 1

Actions, comma-separated, in OSTEP's fork.py notation: a+b means a forks b, b- means b exits. Added for Linux mode: a* means a calls wait and reaps its exited children. Process a is PID 1. Predict before you press Run: with nothing ticked, how many zombies does a+b,b+c,c+d,b-,c-,d- leave?

Process tree
What happened

The rules. Linux: an exiting process becomes a zombie (Z) until its parent waits; its direct children move to the nearest subreaper ancestor, or to PID 1; grandchildren stay where they are; a zombie whose parent is PID 1 stays until PID 1 waits, unless PID 1 reaps (tini does). fork.py default: every descendant of the exiting process moves directly under the root. fork.py -R: the exiting process's children move to its parent. fork.py -L: only leaves may exit. A model of the rules this page states, not a kernel; the real reparenting run above shows Linux's rule. The answer to the prediction: 3 zombies under PID 1 (b's, then c's after a adopted c, then d's after a adopted d), which never waits: exactly the training-script-as-PID-1 problem. Tick "PID 1 reaps" and run again. Checked: the model reproduces all 36 recorded fork.py final trees (seeds 1 to 12; default, -R and -L) and the real reparenting run.

PID 1 is special, twice

Inside a container, the first process gets PID 1 of its PID namespace, and it inherits two duties it may not know about.

  • It must reap orphans. Every orphan in the container becomes its child. A Python training script as PID 1 waits only for children it started through subprocess or multiprocessing; orphans of crashed workers or of shell scripts it ran pile up as zombies (root Debug lab case "Zombies pile up when the training script is PID 1").
  • Signals with no handler do nothing to it. The kernel marks a namespace's init SIGNAL_UNKILLABLE, and sig_task_ignored drops any signal whose action is the default (lines 92 to 93). SIGTERM's default is "terminate", so a PID 1 with no SIGTERM handler simply ignores docker stop, and is SIGKILLed after the grace period: exit 137, no checkpoint. SIGKILL from outside the namespace still works (the comment at line 2838). With a handler installed, as in the running job, PID 1 receives SIGTERM normally.

The usual fix is a tiny init as PID 1 that reaps and forwards signals: docker run --init (Docker ships tini), or tini/dumb-init in the image; but tini forwards SIGTERM to its one child, so its child must be Python, not a shell (the shutdown runs of section 9 found the trap: tini exits with 143 and the kernel kills Python before it can checkpoint).

Knowing when your parent dies: PR_SET_PDEATHSIG, and how DataLoader workers notice (depth)
A child can ask to be signalled when its parent dies: prctl(PR_SET_PDEATHSIG, SIGTERM) (kernel/sys.c line 2470; note that "parent" means the parent thread, so a child started from a short-lived thread gets the signal when that thread exits, PR_SET_PDEATHSIG(2const)). PyTorch's DataLoader workers do not use it; they poll instead: a ManagerWatchdog checks whether os.getppid() still returns the original parent, between waits of MP_STATUS_CHECK_INTERVAL = 5.0 seconds (torch 2.14 torch/utils/data/_utils/worker.py and _utils/__init__.py line 19). So after the trainer is SIGKILLed, its workers notice within about 5 s and exit (root Debug lab case "The main process is SIGKILLed: what happens to its workers").

PID namespaces, and why the container's PID 1 is a different process from the host's, are Containers and isolation.

6. Signals: interrupting a process from outside

ch. 5 (signals in brief); beyond OSTEP: signal(7)

A process is busy running its own code. Sometimes the outside world must interrupt it: the user pressed Ctrl-C, a child died, it touched memory it does not own, the cluster wants the node back. A signal is that interruption: a small number delivered asynchronously, which the process can ignore, let the default action happen, or catch with a function of its own, the handler.

The signals a training job meets

No.NameDefaultSent byIn training
2SIGINTterminatethe terminal on Ctrl-C, to the whole foreground process groupPython turns it into KeyboardInterrupt
9SIGKILLterminateanyone; the OOM killer; the end of every grace periodcannot be caught, blocked or ignored: no checkpoint
15SIGTERMterminatekill, docker stop, the kubelet, Slurm, torchrun"please stop": the one to handle
17SIGCHLDignorethe kernel, when a child exits or stopsthe DataLoader uses it to notice dead workers
7, 11SIGBUS, SIGSEGVcore dumpthe kernel, on a bad memory accessa full /dev/shm; a native crash
13SIGPIPEterminatethe kernel, on a write to a pipe with no readerCPython ignores it, so you get BrokenPipeError instead
10, 12SIGUSR1, SIGUSR2terminateyou, or Slurm's --signal"checkpoint now" or "dump stacks" conventions
19, 18SIGSTOP, SIGCONTstop, continuejob control, debuggers, Slurm before SIGTERMSIGSTOP, like SIGKILL, cannot be caught

Numbers are Linux's on arm64 and x86-64; default actions from the table in include/linux/signal.h. Signals 34 to 64 are real-time signals (glibc keeps 32 and 33 for its threads library).

Generated, pending, delivered

A signal has a life in three stages, and most bugs live between them: it is recorded first and acted on later, only when the thread returns to user mode with it unblocked.

Predict: a process blocks SIGUSR1 and SIGRTMIN, sends itself 1,000 of each, then unblocks them. Its handler counts arrivals. What does it count?

Fig. 5, step by step: kernel functions at v6.12, counts from this page's run

  1. Generated. kill(pid, SIGTERM) is a system call; it enters __send_signal_locked in the kernel.
  2. Dropped if ignored. prepare_signal drops it at once if the target ignores it (and for PID 1, if no handler is installed: section 5).
  3. Pending: one bit per standard signal. It is recorded in a pending set: the thread's own (for a signal aimed at one thread, such as a SIGSEGV caused by that thread) or the process's shared one (for kill to a PID). A standard signal that is already pending is not recorded again: legacy_queue returns true for "sig < SIGRTMIN and already a member", and the second one is lost.
  4. Real-time signals queue. They are queued one by one, each with its sender's information, up to the RLIMIT_SIGPENDING limit (39,345 here).
  5. Blocked by the mask, or a thread is woken. A thread that has the signal blocked (in its mask, set with sigprocmask or pthread_sigmask) leaves it pending until it unblocks. complete_signal picks a thread that is not blocking it and wakes it.
  6. Delivered on the way back to user mode. Only when that thread is about to return to user mode (after a system call, an interrupt, or being scheduled) does get_signal take it off the pending set and act. For a handler, the kernel writes a frame on the user stack with the interrupted registers and points the program counter at the handler.
  7. Back through rt_sigreturn. When the handler returns, a trampoline calls rt_sigreturn, which restores everything from the frame, and the interrupted code carries on as if nothing happened.

What a handler may do: async-signal safety

A handler runs in the middle of whatever the thread was doing, possibly halfway through malloc with the allocator's lock held, or halfway through printf with stdout's lock held. If the handler then calls malloc or printf, it waits for a lock its own thread holds: a deadlock that happens once in a thousand runs. POSIX lists the functions that are safe to call from a handler, the async-signal-safe ones (write, _exit, kill, sigaction and a few dozen more; not malloc, printf, or anything that takes a lock; signal-safety(7)). The safe patterns are: set a volatile sig_atomic_t flag and return; write one byte to a pipe that the main loop watches (the "self-pipe trick"); or block the signal and receive it as data, with sigwaitinfo or a signalfd, a descriptor you can read and put in epoll like any other (signalfd(2)).

Python's handlers run later, and only in the main thread

CPython installs one C handler for every signal you register. It does the async-signal-safe minimum: it records the signal number and sets a flag (and writes to the wakeup descriptor if one was set). Your Python function runs later, at the next bytecode, and always in the main thread (signal docs). So the question that matters for preemption is: how long until the main thread next executes bytecode? Measured: a timer thread sent SIGTERM 0.2 s into each kind of work (src/runs/py/handler_latency.py):

The signal documentation, word for word (source)

"the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point (for example, at the next bytecode instruction)", and "Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread".

When the main thread is running Python or is blocked in an interruptible wait (sleep, a lock with a timeout), the handler runs within a few milliseconds (0.1 to 0.2 ms in a Python loop, 0.2 to 0.3 ms in a lock wait, 0.3 to 2.8 ms in time.sleep): the C handler interrupts the wait (which PEP 475 then resumes). When the main thread is inside one long call into C or C++, the handler waits for the call to return: about 1.2 s for one torch.linalg.solve on 4,000 × 4,000 matrices, the whole remaining duration. The np.sort row shows the same in two of three runs; in one run the handler ran after 70 ms, which these runs do not explain. On a GPU node the long calls are a torch.cuda.synchronize(), a blocking .item(), or a collective waiting for a peer that will never answer: the handler cannot run until it returns, which is why preemption-safe training sets collective timeouts and keeps the grace period longer than the slowest step. (GPU not run here.)

A Python handler waits for the C call the main thread is in

Reading a process's signal state

/proc/<pid>/status shows five masks in hex: SigPnd and ShdPnd (pending for this thread, and for the whole process), SigBlk (blocked), SigIgn (ignored), SigCgt (caught by a handler). Bit n - 1 stands for signal n. Decode the real masks of the running job and its worker, or paste your own:

The job's real masks: SIGINT ignored by a background start, torch's handlers in the worker

The same SIGTERM ends in a checkpoint, a late checkpoint, or SIGKILL

Measured endings: exec form, exit 0 after 0.72 to 0.82 s, the checkpoint (write, fsync, rename, fsync the directory) taking 5 to 9 ms in the three logs; sh -c, exit 137 after 10.30 to 10.38 s, no checkpoint. The middle ending adds the measured C++ call to the first: derived, not one run.

One SIGTERM, three endings

The scheduler's "please stop" reaches the job. The same SIGTERM, three situations: a handler and a main thread running Python (the running job, started directly as PID 1); a handler, but the main thread inside a long C++ call; and no handler reachable, because PID 1 is a shell that does not forward it. Times are the shutdown runs of section 9 and the latency table above. Predict which of the three writes a checkpoint, then step through each.

Fig. 6, step by step: lanes for the runtime, the kernel, the trainer's main thread and its workers

  1. SIGTERM to PID 1 (0 s). docker stop (or the kubelet deleting the pod) asks the container runtime to send SIGTERM to PID 1, here python train.py itself (exec form).
  2. Handler installed: deliver. PID 1 is protected from signals with no handler, but SigCgt has bit 15 set (train.py's handler), so the signal goes pending and the kernel wakes the main thread.
  3. The C handler sets a flag. CPython's C-level handler records "signal 15 arrived" and returns. Nothing else happens in the handler itself.
  4. Python handler: stop = True (0.2 ms). At the next bytecode the interpreter runs on_sigterm, which only sets stop and prints "got signal 15". Measured latency for a main thread running Python: 0.1 to 0.2 ms.
  5. Finish the step. The loop completes the current optimizer step, checks stop and leaves the loop. The model is never saved half-updated.
  6. Checkpoint (5 to 9 ms). save_checkpoint: write ckpt.pt.tmp, fsync, rename over ckpt.pt, fsync the directory (ckpt_begin to ckpt_end took 5 to 9 ms in the three logs).
  7. Workers shut down. del it makes the DataLoader send each worker a stop message, then join them; they exit 0.
  8. Exit 0 (0.72 to 0.82 s). PID 1 exits with 0 and the container stops: docker stop returned after 0.72 to 0.82 s in three runs (variant "exec form", section 9).

The ten start-up variants behind the third ending are in section 9; signals inside event loops (set_wakeup_fd, loop.add_signal_handler) are Concurrency.

7. File descriptors: three tables, pipes and sockets

ch. 39 Files and Directories (open file table, fork and dup)

A process uses files, pipes, sockets, terminals and devices, and the kernel must not hand it raw pointers to any of them. So it hands out small integers, file descriptors, that index a table the kernel keeps for that process. "Everything is a file" in Unix really means "everything is reached through a descriptor": the same read, write, close and poll work on all of them.

Three tables, not one

1. Per process: the fd table, an array of pointers indexed by fd number plus a close-on-exec bit per fd. 2. System-wide: open file descriptions, one per open() call, holding a reference count, the open flags and the current offset. 3. The object: the inode of a file on disk, a pipe's buffer, a socket, a terminal. Fig. 7 draws every state from this page's model of the kernel's rules (lowest free fd, fork copies the table, exec closes close-on-exec fds, EOF when no write end remains):

Fig. 7, step by step: the offset lives in the description, so fork and dup share it and a second open does not

  1. fds 0, 1, 2: one description of the terminal. Every process starts with three descriptors that point at one open file description of the terminal.
  2. open("train.log"): a new description, the lowest free fd. The kernel makes a description with offset 0 that points at the file's inode, and gives it fd 3, the lowest free number.
  3. fork copies the table, not the descriptions. The child's fds 0 to 3 point at the same descriptions as the parent's: the reference counts go up (refs 2 on train.log).
  4. A write moves the shared offset. The parent writes "PARENT\n", 7 bytes, through fd 3: the description's offset becomes 7, and the child's fd 3 is at 7 too.
  5. A second open(): its own offset. The child opens the same file again and gets fd 4: a new description, offset 0, pointing at the same inode. Two offsets on one file.
  6. dup2(3, 5): a second fd, the same description. fd 5 in the child now refers to fd 3's description (refs 3): dup and fork share the offset; only open() makes a new one.
The three structures in the kernel source (v6.12) (reference)

The fd table is struct files_struct; the first 64 slots are built in (NR_OPEN_DEFAULT is the word size, line 24) and it grows as needed. A description is struct file: the reference count f_count (line 1033), the flags you opened with f_flags (1040) and the offset f_pos (1051).

The lowest free fd rule is what makes close(1); open("log") redirect stdout, and why fd numbers in the listings below are reused; fork copies the table with dup_fd (section 3). Measured (src/runs/c/fdshare.c, parent writes "PARENT", child writes "child", three times each):


Case 1 is why a parent and its workers can all write to an inherited log file without destroying each other's lines (with O_APPEND each write also lands at the current end, atomically). Case 2 is two descriptions with two offsets: each process writes from offset 0 and they overwrite each other, leaving "NT" from a "PARENT" line at the end.

Pipes: a 64 KiB buffer, and EOF that needs every writer gone

A pipe is a kernel buffer with a read end and a write end, each a description. A writer that fills the 65,536-byte buffer blocks (or gets EAGAIN if non-blocking) until the reader drains it; that is how a slow consumer slows the producer, the back-pressure every pipeline relies on. Writes of up to PIPE_BUF (4,096) bytes are atomic: they never interleave with another writer's (pipe(7)); bigger writes can. The default size comes from PIPE_DEF_BUFFERS = 16 pages (pipe_fs_i.h line 5) and can be raised per pipe to pipe-max-size (1 MiB here) with F_SETPIPE_SZ. Writing to a pipe whose read ends are all closed raises SIGPIPE, or EPIPE where SIGPIPE is ignored, as in Python, where it becomes BrokenPipeError (python train.py | head).

Pipe capacity and atomicity on this kernel (raw output of pipes.c)

Rewiring descriptors, step by step

pipe, fork, dup2, close and exec on the three tables. Redirections apply left to right, so 2>&1 > log copies stderr from the terminal before stdout moves to the log, and tracebacks still go to the terminal; > log 2>&1 is the right order. The tool beside this text runs the same model on any script and never plays by itself: it opens on the last frame of python train.py 2>&1 | tee log; pick another example (both orders of 2>&1, the leak, the shared offset) and step, or write your own.

The leak and the fix, timed (raw output of cloexec.c)

Python made the fix the default: since 3.4 "newly created file descriptors are non-inheritable" (PEP 446), and subprocess closes everything except 0, 1 and 2 in the child (close_fds=True). C, C++ and Rust code, and libraries that call fork and exec themselves, still need O_CLOEXEC, pipe2(O_CLOEXEC), SOCK_CLOEXEC and accept4(SOCK_CLOEXEC). Rust's standard library sets close-on-exec on everything it opens.

A reader sees end of file only when no descriptor anywhere still refers to a write end

The tables are simulated by this page's model of the kernel's rules (lowest free fd, fork copies the table, exec closes close-on-exec fds, EOF when no write end remains); the leak and fix programs and their timings are real: src/runs/c/cloexec.c.

Write your own script

One operation per line, processes by number: proc 1 sh, tty 1, pipe 1 or pipe 1 O_CLOEXEC, open 1 log O_WRONLY|O_CREAT|O_TRUNC (add |O_CLOEXEC), fork 1 2 name, dup2 2 4 1 (pid, old, new), close 2 3 4, exec 2 python, write 2 1 text\n, read 3 0, exit 2. Then pick "your own script" above.

Descriptors that travel: how batches reach the trainer

A DataLoader worker does not copy a batch to the main process. It creates a file in /dev/shm, maps it, deletes its name at once, and sends the descriptor over a Unix domain socket; the main process maps the same memory. The job's real tables below show the result: files named torch_29_... open in the main process, created by worker PID 29.

Passing a descriptor between processes uses sendmsg with an SCM_RIGHTS control message on a Unix socket: the kernel installs a new fd in the receiver pointing to the same description (unix(7)). PyTorch calls this the file_descriptor sharing strategy, the default on Linux, and it warns that it keeps one descriptor open per shared tensor, so code that keeps many batches alive can hit the open-file limit; the alternative file_system strategy names files instead and can leak them if a process dies (torch.multiprocessing, sharing strategies). The root's Debug lab reproduces "OSError: [Errno 24] Too many open files".

The descriptor tables of the job's main process and a worker, read line by line (real data)

Here are the descriptor tables of the job's main process and one DataLoader worker from the same snapshot as section 1 (ls -l /proc/<pid>/fd shows what each fd refers to; pipes and sockets are named by their inode number):

Main process
Worker

Read them together. fds 4 to 8 are identical in both: the same pipes (inodes 1066456 and 1066457), because the worker got them by fork. fd 5 is the memory-mapped dataset, inherited too. The worker's fd 9 is /dev/null: multiprocessing points a child's stdin there. The interesting ones are the /dev/shm/torch_* files. A worker puts each batch in shared memory: it creates a file in /dev/shm, maps it, deletes its name at once (the listing of /dev/shm below is empty: the files exist only through open descriptors and mappings), and sends the descriptor to the main process over a Unix domain socket (multiprocessing's resource sharer listens on one in the sending process; the worker's fd 15 is a socket). The main process's fds 14 and 15 are files whose names say torch_29_...: they were created by the worker with PID 29 and arrived through that socket. Two descriptors in the main process were closed while ls was reading the table; the listing shows the moment, not a stable state.


Unix domain sockets

A Unix domain socket is a socket whose address is a path (or an abstract name) on the same machine: no network stack, no checksums, two-way, and it can carry descriptors and the sender's credentials. multiprocessing's forkserver talks to its server over one and passes the new worker's pipes through it; Docker's API is /var/run/docker.sock; NCCL and many inference servers use them for local control channels. Network sockets are Networking foundations.

How read and write on a file reach the disk (page cache, fsync) is Storage and file systems; waiting on many descriptors at once (epoll) is Concurrency.

8. Process groups, sessions, limits and identity

beyond OSTEP: credentials(7), getrlimit(2)

Process groups and sessions: who gets signalled together

Every process belongs to a process group (identified by a PGID, the PID of its first member) and every group to a session (SID). A child inherits both. They exist for job control: a shell puts each pipeline in its own group, and the terminal sends Ctrl-C's SIGINT to every process in the foreground group at once. kill(-pgid, sig) (Python os.killpg) does the same from code. setsid() starts a new session and group, detached from any terminal: what daemons do, and what start_new_session=True does in subprocess (credentials(7) describes both).

Two consequences for training:

  • Ctrl-C reaches the workers too. In a terminal, the trainer and its DataLoader workers are one foreground group, so all of them get SIGINT. The workers catch the resulting KeyboardInterrupt and exit quietly ("Main process will raise KeyboardInterrupt anyways", torch 2.14 _utils/worker.py line 396), and the main process unwinds.
  • torchrun signals groups, not processes. torchrun starts each trainer with start_new_session=True (subprocess_handler.py), so each trainer leads its own session and group, and its DataLoader workers join that group. To stop a trainer it calls os.killpg(trainer_pid, SIGTERM). In the recorded process tree under torchrun (section 9), PGID and SID of the trainer and its two workers are all the trainer's PID; the SIGTERM therefore reaches the workers directly, which section 9 shows has a cost.

Resource limits

Each process carries soft and hard resource limits: the soft one is enforced, and a process may raise it up to the hard one (only a privileged process can raise the hard one). They are inherited across fork and exec, which is why ulimit -n 65536 in a launcher script applies to everything it starts. Two bite training jobs most: open files (Docker here sets 1,048,576, but many hosts and Slurm jobs start with a soft limit of 1,024, which the file_descriptor tensor-sharing strategy and many-shard data loaders exceed: Errno 24) and locked memory (64 KiB here; RDMA pins buffers against it, so GPU containers run with --ulimit memlock=-1).

Change them with ulimit in a shell, prlimit --pid <pid> for a running process, resource.setrlimit in Python, docker run --ulimit, or Slurm's --propagate.

The job's limits from the snapshot, and why each matters (reference)

LimitHereWhy it matters in training
Max open files (RLIMIT_NOFILE)1,048,576Docker here sets it high; many hosts and Slurm jobs start with a soft limit of 1,024, which the file_descriptor tensor-sharing strategy and many-shard data loaders exceed: Errno 24
Max core file size0 softNo core dump when a worker segfaults until you raise it (ulimit -c unlimited)
Max locked memory (RLIMIT_MEMLOCK)64 KiBRDMA (InfiniBand, RoCE) registers and pins buffers, which counts against this limit; NVIDIA's container guide runs its framework images with --ulimit memlock=-1 (unlimited) (NGC containers user guide); not run here
Max processes (RLIMIT_NPROC)unlimitedCounts threads per user; in containers the cgroup's pids.max usually bites first
Max pending signals39,345The real-time signal queue limit of section 6
Max stack size8 MiBThe main thread's stack; deep recursion in C extensions
Identity: user ids, capabilities and no_new_privs (depth)

A process has a real user id (who started it), an effective user id (whose permissions it uses), a saved id (so a privileged program can drop and regain privilege), and group ids likewise; the Uid: line in status lists real, effective, saved and file-system ids, all 0 for the job. Root inside a container is not all of root: the effective capability set CapEff 00000000a80425fb is Docker's reduced default set, and Seccomp: 2 shows a filter on system calls. Capabilities, user namespaces and seccomp are the containers child page. One flag belongs here because it is inherited like a limit: prctl(PR_SET_NO_NEW_PRIVS) makes sure no exec'd program can gain privileges (no set-user-ID), and once set it cannot be cleared; sandboxes for untrusted code rely on it.

9. In a training job: start methods, the DataLoader, torchrun, preemption

Everything above, assembled into the processes a training node actually runs.

Start methods, by Python version

PythonLinux defaultmacOS defaultNotes
3.7 and earlierforkfork
3.8 to 3.11forkspawnmacOS changed because "macOS system libraries may start threads" (3.11 docs)
3.12, 3.13forkspawnos.fork() warns (DeprecationWarning) when it detects other threads
3.14forkserverspawn"the default start method was changed from fork to forkserver" on POSIX (3.14 docs)

The DataLoader uses the multiprocessing default unless you pass multiprocessing_context. Costs on this machine (section 3 and the root): a fork worker is ready in milliseconds; a spawn or forkserver worker needs a fresh interpreter that imports torch, about 0.65 to 0.94 s, paid again at every epoch unless persistent_workers=True. With forkserver, multiprocessing.set_forkserver_preload(["torch"]) pays the import once in the server (the root measured 0.035 s per new iterator after a 0.703 s first one). Name the start method in code; do not let a Python upgrade choose it.

The DataLoader's worker processes, from the source

Read from torch 2.14's torch/utils/data/dataloader.py and _utils/worker.py inside the lab image. Every arrow in the figure is a mechanism from sections 3 to 7:

In short: each worker is a daemon multiprocessing.Process with its own index queue and a shared result queue; it installs torch's C handlers (the worker SigCgt of section 6), runs with one thread, and polls whether its parent still lives; the main process notices a dead worker through SIGCHLD and raises in the main thread; shutdown is a stop message and a join with a timeout.

The five stages from the source, with line numbers (depth)
  1. Start. iter(loader) creates one index queue per worker and one shared result queue, then starts each worker as a multiprocessing.Process with daemon = True (line 1168), so it is killed if the main process exits normally without shutting it down. The main process installs its SIGCHLD handler (_set_SIGCHLD_handler).
  2. Worker set-up. In _worker_loop each worker installs C-level handlers for SIGBUS, SIGSEGV, SIGFPE and SIGTERM that print an error and die (exactly the worker SigCgt decoded in section 6), names its thread pt_data_worker (the comm in section 1), sets torch.set_num_threads(1), seeds its random generators with base_seed + worker_id, and calls your worker_init_fn.
  3. Loop. While the ManagerWatchdog sees the original parent (section 5), it waits up to MP_STATUS_CHECK_INTERVAL = 5.0 s for an index, builds the batch, and puts it on the result queue; tensors travel as shared-memory descriptors (section 7).
  4. Failure. If a worker dies, the main process gets SIGCHLD; its handler calls _error_if_any_worker_fails(), which uses waitid to find a worker that died and raises RuntimeError: DataLoader worker (pid N) is killed by signal: ... in the main thread, wherever it is (the NOTE at the top of signal_handling.py).
  5. Shutdown. When the iterator is deleted or exhausted, _shutdown_workers sets a done event, sends each worker a stop message, joins each with a timeout of 5.0 s, and terminates any that remain. Workers are re-created for the next epoch unless persistent_workers=True.

Workers are forked children fed by queues; the main process learns of a death through SIGCHLD, a worker of an orphaning through polling

torchrun, and the trap in its shutdown

torchrun runs an elastic agent that starts one trainer process per GPU (environment variables RANK, LOCAL_RANK, WORLD_SIZE, MASTER_ADDR, MASTER_PORT tell each who it is), each in its own session (section 8), then polls them. If one fails it stops the others and, up to --max-restarts, starts the group again. For a stop request it registers handlers for SIGTERM, SIGINT, SIGHUP and SIGQUIT (overridable with TORCHELASTIC_SIGNALS_TO_HANDLE); the handler raises SignalException, the agent sends SIGTERM to each trainer's process group, waits up to 30 s, then sends SIGKILL, and finally re-raises, so torchrun itself exits 1 (torch 2.14 torch/distributed/elastic/multiprocessing/api.py lines 76 to 86 and 1023 to 1068; elastic agent docs).

Predict: the running job, whose SIGTERM handler sets a flag and checkpoints after the step, is launched with torchrun --nproc-per-node 1 and two DataLoader workers. docker stop sends SIGTERM to torchrun. Does the trainer write its checkpoint?
def ignore_term(worker_id):                 # runs in each worker, after torch's own handlers
    signal.signal(signal.SIGTERM, signal.SIG_IGN)
loader = DataLoader(ds, num_workers=2, worker_init_fn=ignore_term,
                    multiprocessing_context="forkserver", persistent_workers=True)

The runs used a wrapper (src/runs/py/ignore_term_in_workers.py) that adds this worker_init_fn to the root's unchanged train.py. The same group-signal effect appears without torchrun when anything signals the whole group (pkill -f train.py, kill -- -PGID): the root's Debug lab case "pkill -TERM also hits the workers".

Ten ways to start the job, and what docker stop did

Ten ways to start the same training job in a container, and what docker stop did to each. docker stop -t 10 sends SIGTERM to the container's PID 1, waits 10 s, then sends SIGKILL: the same sequence as a Kubernetes pod deletion or a Slurm cancellation, with a shorter grace period.

  • Whether Python is PID 1 decides everything. The exec form, sh -c "exec ..." and bash -c (bash replaces itself with a single simple command, which is why the same line works on some images and not others) made Python PID 1: clean stop in under a second. Plain sh -c left dash as PID 1, which neither forwards SIGTERM nor dies from it (section 5): 10.3 to 10.4 s, exit 137, every run.
  • An init is not a fix by itself. --init forwards SIGTERM to its one child; a shell child dies at once (it is not PID 1, so the default action applies), tini exits with 143, and the kernel kills the rest of the namespace: no checkpoint, in a third of a second. TINI_KILL_PROCESS_GROUP=1 does not help, because the shell still dies first. With Python as tini's direct child everything works, and orphans are reaped too.
  • torchrun signals process groups (the trap above); ignoring SIGTERM in the workers fixed it in all three runs, and torchrun still exits 1 after a death signal by design.
Predict: docker run --init image sh -c "python train.py; echo done", then docker stop. The Python script has a correct SIGTERM handler. Checkpoint written?

Only the starts that make Python PID 1, or tini's direct child, checkpoint before the SIGKILL line

How the runs were made, and the selected variant's command, process tree and log (real data; click a row above to choose)

The job is the root's running example (src/trace/job/train.py: SIGTERM handler that sets a flag, checkpoint after the step, exit 0) with 2 fork DataLoader workers, 2 CPUs, in kb-os-lab:1 (Debian 12: dash 0.5.12 as sh, bash 5.2.15; Docker 20.10.17, whose --init is tini). Each variant ran 3 times, 2026-10-05: started, waited for training step 5, recorded the process tree with ps, then timed docker stop and read the exit code and the log. Script: src/runs/run_shutdown.sh; raw records: src/runs/out/shutdown/.

In the "--init, exec form" runs the recorded tree caught two workers of the previous epoch as zombies (Z, <defunct>) for a moment, between their exit and the DataLoader's join; tini, as PID 1, would reap any that were orphaned.

Graceful preemption, end to end

KubernetesSlurm
Who gets SIGTERMPID 1 of each container ("send a TERM signal to process 1 inside each container", Pod Lifecycle)scancel sends "first a SIGCONT to all steps to eventually wake them up followed by a SIGTERM, then wait the KillWait duration" before SIGKILL (scancel(1))
Grace periodterminationGracePeriodSeconds, default 30 s; a preStop hook runs first, inside the same periodKillWait in slurm.conf
Warning before a time limitnone built in--signal=B:USR1@120: "Use the "B:" option to signal only the batch shell", so the batch script must forward it; without B:, "all job steps will be signaled, but not the batch shell itself" (sbatch(1))
Classic failurePID 1 is a shell (sh -c) that neither forwards nor exits: 30 s, then SIGKILLThe batch shell catches the signal with trap while blocked in a foreground command; bash runs the trap only after that command finishes (Bash manual, Signals), so start the job in the background and wait
The checklist
  1. Make the trainer PID 1 or have PID 1 forward signals: the exec form in the Dockerfile, exec python ... in scripts, or a real init (--init, tini) whose child is Python itself, not a shell (the shutdown runs above).
  2. Install a SIGTERM handler that only sets a flag; checkpoint in the loop, after the step, with the write-fsync-rename pattern of the storage page.
  3. Make DataLoader workers ignore SIGTERM when anything may signal the whole group (torchrun does).
  4. Keep the slowest step, plus the checkpoint, shorter than the grace period; set collective timeouts so a dead peer cannot hold the main thread past it (section 6).
  5. Exit 0 after a requested stop, so the scheduler does not count it as a failure and restart it in a loop; check how your launcher reports it (torchrun exits 1).

Kubernetes resources and their cgroups are the containers child page and Topic: ml-infra-and-orchestration; collectives, timeouts and elastic training are Distributed Training and Fault tolerance at scale; DataLoader APIs are Topic: pytorch-ecosystem.

10. Depth: interview rehearsal and the OSTEP map

Interview rehearsal: nine questions, with model answers (optional)
What happens, step by step, when a program calls read()?
The libc wrapper puts the call number and arguments in registers and executes the trap instruction (svc on arm64, syscall on x86-64). The CPU switches to kernel mode and jumps to the kernel's entry; the kernel saves registers, looks the number up in the system-call table, runs sys_read (fd table, then the file's read method, often a copy from the page cache), stores the result in the return register and returns to user mode. The wrapper turns a negative result into errno and -1. A few hundred nanoseconds when nothing blocks.
What is the difference between a process and a thread on Linux?
Both are tasks made by clone. Threads share the address space, descriptor table, signal handlers and thread group id (flags CLONE_VM | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD...); a process gets copies. Threads share memory cheaply and crash together; processes are isolated and each has its own GIL in CPython.
Why does fork return twice, and what does the child inherit?
The kernel creates a second task that resumes from the same point; it sets the return register to 0 in the child and the child's PID in the parent. The child gets copies of the address space (copy-on-write), the descriptor table (same open file descriptions, shared offsets), signal handlers and mask, credentials, limits and current directory; not pending signals, timers, locks or other threads.
What is a zombie, and how do you get rid of one?
A process that has exited but whose parent has not yet called wait; only its PID and exit status remain. You cannot kill it (it is already dead): the parent must wait, or die so that init or a subreaper adopts and reaps it. In containers, make sure PID 1 reaps (an init such as tini).
Why might docker stop take 10 seconds and end with 137?
SIGTERM went to PID 1, which ignored it: either PID 1 has no handler (a namespace's init drops default-action signals) or it is a shell that does not forward. After the grace period Docker sent SIGKILL: 128 + 9 = 137.
Can a signal handler call printf or malloc?
No: they are not async-signal-safe. The handler may have interrupted the same function holding the same lock, and would deadlock. Set a sig_atomic_t flag, write to a pipe, or receive signals synchronously with signalfd or sigwaitinfo.
What is the difference between a file descriptor and an open file description?
The descriptor is an index in one process's table; the description is the kernel object created by open, holding the offset and flags. dup and fork create new descriptors for the same description (shared offset); a second open creates a new description.
Why can a reader of a pipe hang even after the writer closed it?
EOF requires every write-end descriptor in every process to be closed. A forked or exec'd process that inherited a write end keeps the pipe open. Close unused ends after fork and use O_CLOEXEC.
How would you make a PyTorch job survive preemption?
The trainer receives SIGTERM directly (exec form or a forwarding init); its handler sets a flag; the loop checkpoints atomically after the step and exits 0; DataLoader workers ignore SIGTERM so a group signal cannot crash the trainer first; steps and collectives are bounded so the grace period is enough; resume from the last checkpoint on restart.
The OSTEP chapters this page follows, and what it adds to each (reference)
OSTEPHereWhat this page adds
ch. 4 The Abstraction: The Process (and its homework process-run.py)section 1task_struct, threads as tasks, real /proc of a training job, Linux's state letters
ch. 5 Interlude: Process API (homework fork.py)sections 3 to 5 (the tree simulator in 5)clone flags, vfork and posix_spawn with measured costs, what exec keeps, reaping and PID 1; the tree simulator is checked against fork.py
ch. 6 Limited Direct Executionsection 2the real arm64 instructions, kernel entry functions, errno, strace's cost
ch. 39 Files and Directories (fork and dup sharing)section 7the three tables in the kernel source, pipes, close-on-exec, descriptors passed between processes
not in OSTEPsections 6, 8, 9signals in depth, sessions and process groups, limits, credentials, the DataLoader, torchrun and preemption

OSTEP chapter numbers from the v1.10 table of contents (OSTEP). The classic deeper reference for everything on this page is Michael Kerrisk's The Linux Programming Interface (chapters 20 to 28, 34, 44 and 61), listed under Further reading.