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
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).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.getppid measured here, section 2).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).
getpid() returns.errno.killpg); a session is what setsid starts.| Call | What it does | Cost measured here | Where it bites in ML work | See it with |
|---|---|---|---|---|
read, any syscall | Enter 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 strace | Millions of tiny reads in a data loader; profiling with strace distorts timings 460-fold | strace -c -f, perf trace |
fork | Copy 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 pages | DataLoader workers under the fork start method; fork after CUDA or threads | strace -e clone, /proc/<pid>/status VmPTE |
posix_spawn, vfork | Start a new program without copying the parent's page tables | about 0.39 ms, whatever the parent's size | subprocess from a big trainer (Python already uses it) | strace -e clone,clone3,execve |
execve | Replace the program in this process; keep PID and non-CLOEXEC descriptors | part of spawn: a fresh Python with torch is about 0.9 s | spawn and forkserver workers re-import torch | strace -e execve |
wait4, exit | Collect a child's exit status; until then it is a zombie | a zombie costs a PID and a little kernel memory | Zombie workers when the script is PID 1 in a container | ps -o stat (Z) |
kill, rt_sigaction | Send a signal; choose what it does on arrival | Python 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, close | Make and rewire descriptors; a pipe holds 64 KiB | a leaked write end delayed EOF by 2.0 s (until the leaker exited) | Hangs waiting for EOF; "Too many open files" with tensor sharing | ls -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.
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.
| Field (v6.12 line) | What it holds | Shared by threads? | Section |
|---|---|---|---|
| __state (786) | Running, sleeping, stopped...; the letter ps shows | no, per task | below |
| mm (921) | The address space: page tables and mappings | yes | 3, and the virtual memory page |
| exit_state, exit_code (925 to 926) | Zombie or dead; the status the parent will collect | no | 5 |
| pid, tgid (1018 to 1019) | This task's id; the id of its thread group | tgid yes | below |
| real_parent, children (1032, 1040) | The process tree | per task | 5 |
| cred (1114) | User and group ids, capabilities | usually | 8 |
| comm (1128) | The 15-character name ps shows (pt_data_worker) | no | 9 |
| fs, files (1141, 1144) | Current directory and root; the file descriptor table | yes | 7 |
| nsproxy (1151) | Namespaces: which PIDs, mounts, network it sees | yes | containers page |
| signal, sighand, blocked, pending (1154 to 1160) | Process-wide signal state, the handler table, this thread's mask and private pending set | signal and sighand yes; blocked and pending no | 6 |
| thread (1602) | The CPU registers saved while the task is not running | no | scheduling page |
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)).
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.
The one-letter state comes from a table in fs/proc/array.c line 126:
| Letter | Kernel name | Meaning | Where you meet it in training |
|---|---|---|---|
| R | running | On a CPU or ready to run (OSTEP separates running from ready; Linux shows both as R) | The training loop computing; a busy worker |
| S | sleeping | Waiting for an event; a signal can wake it (interruptible) | Workers waiting on their index queue; main waiting for a batch |
| D | disk sleep | Waiting inside the kernel, uninterruptible: not even SIGKILL acts until the wait ends | Page 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, t | stopped, tracing stop | Stopped by SIGSTOP or Ctrl-Z; stopped by a debugger or strace | A job paused by kill -STOP; every system call under strace |
| Z | zombie | Exited; its parent has not collected the status yet | Section 5 |
| X | dead | Being removed; you will almost never see it | |
| I | idle | A 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.
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
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.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).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.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.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.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.cmn x0, #0x1, lsl #12 compares 27 with -4096. Not in -4095..-1, so it is a byte count, and glibc returns 27.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).fd 3 was closed earlier. CPython allocates the buffer and releases the GIL exactly as before.read(3, buf, 4096). Arguments in x0 to x2; the cancellable path, because the process has threads.svc #0. x8 = 63; the CPU switches to kernel mode. Mode switch 1.pt_regs; SVC64; do_el0_svc with regs[8] = 63.sys_read: fd 3 is not open. The descriptor table has no file at index 3 (it was closed earlier). sys_read returns -EBADF, which is -9. No data moves.eret. The kernel writes -9 into the saved x0. The kernel never touches errno: that is a C-library idea. Mode switch 2.errno through tpidr_el0, stores 9 (EBADF) there, and returns -1.OSError: [Errno 9] Bad file descriptor. os_read_impl sees -1, reads errno = 9 and builds the exception with PyErr_SetFromErrno; it surfaces at your line. The same path gives FileNotFoundError (errno 2), PermissionError (13), BlockingIOError (11).strace, which attached to this process with ptrace.read(3, buf, 4096). Arguments in x0 to x2, the cancellable path.svc #0. x8 = 63; kernel mode. Mode switch 1.do_el0_svc.el0_svc_common sees the syscall-trace flag that ptrace set, and ptrace_report_syscall_entry stops this thread (state "t, tracing stop"); the scheduler switches to something else. strace, blocked in wait4, returns with "stopped at syscall entry", asks for the registers with ptrace, decodes call 63 with x0 = 3, prints read(3, , and resumes the thread with ptrace(PTRACE_SYSCALL). Tracer stop 1.sys_read runs as before. 27 bytes from the page cache into buf.ptrace_report_syscall_exit stops the thread a second time; strace reads x0 (27) and the 27 bytes from this process's memory (process_vm_readv or PTRACE_PEEKDATA), prints "hello..."..., 4096) = 27, and resumes it. Tracer stop 2; measured, strace made 4 wait4, 4 ptrace and 2 write calls for this one call, entry and exit together.eret, glibc, CPython: 27 bytes. The same way back, two mode switches in all, but two tracer stops and ten calls of strace's own on the way: about 124 µs per call measured, against 269 ns untraced.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.
| arm64 (this page's runs, Graviton, Grace) | x86-64 (most GPU servers) | |
|---|---|---|
| Instruction | svc #0 ("supervisor call") | syscall |
| Call number in | x8 | rax |
| Arguments in | x0 to x5 | rdi, rsi, rdx, r10, r8, r9 |
| Result in | x0 | rax (the CPU also overwrites rcx and r11) |
Number of read | 63 (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 clone | yes (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.
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.
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):
ESR_ELx_EC_SVC64 (line 729) means "a system call".regs->regs[8], your x8, as the call number.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.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.
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.
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.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.
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 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.
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 */
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
VmPTE, this page's run). The 16 cubes stand for the pages.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.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.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.| Resource | Copy function (v6.12) | Shared if this flag is set | Plain fork (no flags) |
|---|---|---|---|
| Address space | copy_mm then dup_mm and dup_mmap | CLONE_VM | Copied: 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 table | copy_files then dup_fd | CLONE_FILES | Copied table; the entries point to the same open files (section 7) |
| Current directory, root, umask | copy_fs | CLONE_FS | Copied |
| Signal handlers | copy_sighand | CLONE_SIGHAND | Copied: same handlers, same ignored set |
| Thread group | (the tgid) | CLONE_THREAD | New 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).
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.
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.
fork(), and the child exits immediately. How long does fork plus wait take, compared with the same program holding no memory (0.25 ms)?VmPTE grew from 48 KiB to 2,100 KiB: 262,144 entries of 8 bytes) and takes a reference on each page, about 64 ns per 4 KiB page, (17.08 - 0.25) ms / 262,144, including the child's exit tearing the copy down. Copying the data itself would have taken longer still.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.
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.
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.
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.
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
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.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.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.SigCgt 0). SIGUSR2 is still ignored (SigIgn 0x800, signal 12) and SIGHUP still blocked (SigBlk 0x1, signal 1).showself prints open fds: 0 1 2 5.#! scripts, the dynamic loader (depth)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.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.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.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):
| State | After execve | Seen above as |
|---|---|---|
| PID, parent, process group, session | kept | same pid before and after |
| Descriptors without close-on-exec | kept, same offsets | fd 5 still open |
Descriptors with O_CLOEXEC | closed | fd 6 gone |
| Caught signals (handlers) | reset to default | SigCgt all zero |
| Ignored signals | stay ignored | SigIgn 0x800 = signal 12, SIGUSR2 |
| Blocked signals (the mask) | kept | SigBlk 0x1 = signal 1, SIGHUP |
Memory, threads, atexit handlers, stdio buffers | gone | |
| Environment, argv | whatever 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 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.
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.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.
| Call | What it does | Use 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_group | Normal end of a program |
_exit(n), os._exit(n) | The system call exit_group directly: all threads end now; nothing in user space runs | In a forked child that must not run the parent's cleanup |
the exit system call | Ends one thread; what a returning thread function becomes | Never 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):
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?multiprocessing ends every forked child with os._exit(code) (popen_fork.py line 73) for this reason; sys.stdout.flush() before forking is the habit to keep.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".
| Code | Means | Typical training cause |
|---|---|---|
| 0 | exited normally | finished, or caught SIGTERM and checkpointed |
| 1 | exited with 1 | an uncaught Python exception; torchrun after a worker failure or a death signal |
| 137 = 128 + 9 | SIGKILL | the OOM killer, or the grace period ran out after SIGTERM |
| 143 = 128 + 15 | SIGTERM, default action | stopped with no handler installed |
| 139 = 128 + 11, 135 = 128 + 7 | SIGSEGV, SIGBUS | a 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.
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.
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.
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:
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:
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?
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.
Inside a container, the first process gets PID 1 of its PID namespace, and it inherits two duties it may not know about.
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").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).
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.
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.
| No. | Name | Default | Sent by | In training |
|---|---|---|---|---|
| 2 | SIGINT | terminate | the terminal on Ctrl-C, to the whole foreground process group | Python turns it into KeyboardInterrupt |
| 9 | SIGKILL | terminate | anyone; the OOM killer; the end of every grace period | cannot be caught, blocked or ignored: no checkpoint |
| 15 | SIGTERM | terminate | kill, docker stop, the kubelet, Slurm, torchrun | "please stop": the one to handle |
| 17 | SIGCHLD | ignore | the kernel, when a child exits or stops | the DataLoader uses it to notice dead workers |
| 7, 11 | SIGBUS, SIGSEGV | core dump | the kernel, on a bad memory access | a full /dev/shm; a native crash |
| 13 | SIGPIPE | terminate | the kernel, on a write to a pipe with no reader | CPython ignores it, so you get BrokenPipeError instead |
| 10, 12 | SIGUSR1, SIGUSR2 | terminate | you, or Slurm's --signal | "checkpoint now" or "dump stacks" conventions |
| 19, 18 | SIGSTOP, SIGCONT | stop, continue | job control, debuggers, Slurm before SIGTERM | SIGSTOP, 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).
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.
waitpid(-1, ..., WNOHANG) until no child is left, because three children dying together may produce one SIGCHLD. Reading them through a signalfd (part B) gives the same counts: it changes how you receive signals, not how they are queued.Fig. 5, step by step: kernel functions at v6.12, counts from this page's run
kill(pid, SIGTERM) is a system call; it enters __send_signal_locked in the kernel.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.RLIMIT_SIGPENDING limit (39,345 here).sigprocmask or pthread_sigmask) leaves it pending until it unblocks. complete_signal picks a thread that is not blocking it and wakes it.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.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)).
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 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.)
/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:
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.
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
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).SigCgt has bit 15 set (train.py's handler), so the signal goes pending and the kernel wakes the main thread.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.stop and leaves the loop. The model is never saved half-updated.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).del it makes the DataLoader send each worker a stop message, then join them; they exit 0.docker stop returned after 0.72 to 0.82 s in three runs (variant "exec form", section 9).python train.py, PID 1.torch.linalg.solve. The flag is set, but no bytecode runs until the call returns: measured 1.18 to 1.29 s, the whole remaining duration of the call. On a GPU node the same happens inside a blocking synchronize or a stuck collective.stop = True. The call returns and the Python handler finally runs. From here the path is the same as the first case.stop after the step.sh -c "python train.py ...". Debian's dash does not replace itself with python, so PID 1 is the shell, and SIGTERM goes to the shell.sig_task_ignored drops a signal whose action is the default. The shell does not forward anything; python never hears of it.docker stop, 30 s by default on Kubernetes), unaware.sh -c "exec python ...", or the exec form in the Dockerfile.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.
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.
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
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.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.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.pipe(): fd 3 reads, fd 4 writes. One pipe object and two descriptions; neither end is close-on-exec.sleep 2. fd 4 was not close-on-exec, so the sleeping program still holds the pipe's write end without knowing it exists.pipe2(O_CLOEXEC). The same program, but both ends are marked close-on-exec (red cells).execve the kernel closes every close-on-exec descriptor, so the sleeping program holds nothing.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.
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, 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.
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.
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.
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.
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".
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):
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.
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.
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:
KeyboardInterrupt and exit quietly ("Main process will raise KeyboardInterrupt anyways", torch 2.14 _utils/worker.py line 396), and the main process unwinds.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.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.
| Limit | Here | Why it matters in training |
|---|---|---|
Max open files (RLIMIT_NOFILE) | 1,048,576 | Docker 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 size | 0 soft | No core dump when a worker segfaults until you raise it (ulimit -c unlimited) |
Max locked memory (RLIMIT_MEMLOCK) | 64 KiB | RDMA (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) | unlimited | Counts threads per user; in containers the cgroup's pids.max usually bites first |
| Max pending signals | 39,345 | The real-time signal queue limit of section 6 |
| Max stack size | 8 MiB | The main thread's stack; deep recursion in C extensions |
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.
Everything above, assembled into the processes a training node actually runs.
| Python | Linux default | macOS default | Notes |
|---|---|---|---|
| 3.7 and earlier | fork | fork | |
| 3.8 to 3.11 | fork | spawn | macOS changed because "macOS system libraries may start threads" (3.11 docs) |
| 3.12, 3.13 | fork | spawn | os.fork() warns (DeprecationWarning) when it detects other threads |
| 3.14 | forkserver | spawn | "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.
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.
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)._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.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)._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)._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.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).
torchrun --nproc-per-node 1 and two DataLoader workers. docker stop sends SIGTERM to torchrun. Does the trainer write its checkpoint?killpg delivers SIGTERM to the trainer and to its two DataLoader workers, which are in the trainer's process group. The trainer's handler sets its flag, but the workers' C handlers kill them immediately; the trainer gets SIGCHLD, and the DataLoader's handler raises RuntimeError: DataLoader worker (pid ...) is killed by signal: Terminated. in the middle of the forward pass, before the loop can reach its checkpoint. The fix that worked in all three runs: make the workers ignore SIGTERM in worker_init_fn (which runs after torch installs its handler), so only the trainer reacts and then shuts its workers down itself. See the shutdown runs below, variants "torchrun" and "torchrun, workers ignore SIGTERM".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 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.
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.--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.docker run --init image sh -c "python train.py; echo done", then docker stop. The Python script has a correct SIGTERM handler. Checkpoint written?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.
| Kubernetes | Slurm | |
|---|---|---|
| Who gets SIGTERM | PID 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 period | terminationGracePeriodSeconds, default 30 s; a preStop hook runs first, inside the same period | KillWait in slurm.conf |
| Warning before a time limit | none 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 failure | PID 1 is a shell (sh -c) that neither forwards nor exits: 30 s, then SIGKILL | The 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 |
exec python ... in scripts, or a real init (--init, tini) whose child is Python itself, not a shell (the shutdown runs above).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.
read()?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.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.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).docker stop take 10 seconds and end with 137?printf or malloc?sig_atomic_t flag, write to a pipe, or receive signals synchronously with signalfd or sigwaitinfo.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.O_CLOEXEC.| OSTEP | Here | What this page adds |
|---|---|---|
ch. 4 The Abstraction: The Process (and its homework process-run.py) | section 1 | task_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 Execution | section 2 | the real arm64 instructions, kernel entry functions, errno, strace's cost |
| ch. 39 Files and Directories (fork and dup sharing) | section 7 | the three tables in the kernel source, pipes, close-on-exec, descriptors passed between processes |
| not in OSTEP | sections 6, 8, 9 | signals 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.
Every link was checked on 5 October 2026. Times are reading-time estimates for the part worth reading. Suggested order: this page's Reading tab, running the tree simulator (section 5) and the descriptor stepper (section 7) as you go; OSTEP chapters 4 to 6 and the fork.py homework; then The Linux Programming Interface's chapters for whichever call you are debugging.
The root: the whole OS around one training job. Its Syscall tracer tab (every call the job makes; start methods; SIGTERM in the trace), OS simulators tab (schedulers, races and crash consistency, after OSTEP) and Debug lab (zombies, ignored SIGTERM, fork with a held lock, too many open files) are the companions of this page.
What happens to these tasks on the CPU: context switches, CFS and EEVDF, cgroup CPU limits.
The address space fork copies: page tables, copy-on-write, mmap, huge pages, the OOM killer.
malloc, arenas and PyTorch's caching allocator.
Threads, futexes, deadlock, and event loops over descriptors (epoll, io_uring), including signals in event loops.
What read and write do below the descriptor: page cache, fsync, the safe checkpoint.
PID namespaces (why PID 1 is special), cgroups, capabilities and seccomp.
One CUDA call down to an ioctl on a device descriptor.
The GIL, threads and multiprocessing from the language side (section 1).
The other runtimes that end in the same system calls (libstdc++, Rust std and tokio, libuv).
Launchers, collectives, timeouts and elastic restarts at scale.
DataLoader and torchrun APIs; Kubernetes and Slurm; network sockets.
The textbook chapters this page follows, free. Do the cpu-api homework (fork.py and the C exercises).
The open file table, fork and dup sharing, as in section 7.
The definitive book for this page: chapters 20 to 22 (signals), 24 to 28 (process creation, exec, exit, wait), 34 (process groups and sessions), 44 (pipes), 61 (passing descriptors).
The case against fork: its cost with large address spaces, its interaction with threads, and why posix_spawn should be the default. Section 3's measurements in research form.
The kernel side of section 2 on x86-64, including the vDSO (2014, older kernels; the shape is unchanged).
Why a container needs an init, and its options (subreaper mode, signalling the group).
fork(2), clone(2), execve(2), wait(2), signal(7), signal-safety(7), signalfd(2), pipe(7), unix(7), credentials(7), pid_namespaces(7), syscall(2).
kernel/fork.c, kernel/exit.c, kernel/signal.c, fs/exec.c, arch/arm64/kernel/syscall.c.
multiprocessing start methods, signal (execution of handlers), subprocess, torch.utils.data (multi-process loading), torchrun, torch.multiprocessing sharing strategies.
Kubernetes pod termination, sbatch --signal, scancel, Dockerfile shell and exec form.