FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Linux Process Lifecycle & IPC

fork(), execve(), Unix domain sockets, named pipes, and shared memory allocation.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Trace process creation and memory copy-on-write mechanics
  • ✓Build fast inter-process communication using Unix domain sockets
Full Technical Reference Document

Mental model

In POSIX/Linux systems, spawning a new service process decouples cloning (fork()) from binary replacement (execve()). fork() duplicates the parent's task_struct and virtual page tables virtually instantaneously using Copy-on-Write (CoW) shared physical pages (copying a page only upon modification), while execve() scrubs and overlays the child's address space with target program text—after which terminated children stay in Zombie (Z) state cleanly until the parent reaps exit codes via waitpid().

Parent invokes fork() -> CoW page share
Child swaps image via execve('/app')
Fast local IPC: AF_UNIX vs shm mmap
Child calls _exit(code) -> enters Zombie
Parent reaps via waitpid() freeing PID
Conceptual teaching model synthesized from:linux-kernel-docs,sre-book

Learning outcomes

  • Trace OS memory mechanics during fork(), why Copy-on-Write keeps read-only code/tables fast cleanly—and how mutating parent-shared objects (Python refcounts) triggers hidden RAM spikes!
  • Diagnose and prevent Zombie (Z) PID exhaustion (never just kill -9 a zombie cleanly—reap via parent waitpid or PID 1 init) and distinguish orphan re-parenting cleanly.
  • Choose properly across Unix Domain Sockets (AF_UNIX), anonymous pipes, and POSIX shared memory (shm_open + mmap) for high-throughput local worker IPC cleanly.

Theory

When multi-worker ML inference servers (vLLM, Gunicorn, PyTorch DataLoader) communicate across local GPU workers, sidecar proxies (Envoy/Postgres), or sub-processes on the same Linux node, crossing local AF_UNIX or mmap avoids kernel TCP/IP checksums, SYN routing tables, and loopback fragmentation cleanly:

Local IPC PrimitiveTransport Semantics & CopyingThroughput & LatencyConcurrency & Security Notes
Pipes (pipe())Unidirectional byte stream cleanly across related parent/child FDs~GB/s kernel buffer copies (splice/sendfile avoid extra user hops)Blocks silently if unread 64 KB pipe buffer fills (deadlock trap!)
Unix Domain Sockets (AF_UNIX)Full-duplex SOCK_STREAM / SOCK_SEQPACKET; enforces filesystem UID permissions; passes FDs (SCM_RIGHTS)!2x–4x faster local RTT than TCP 127.0.0.1Ideal cleanly for Nginx and Postgres/Gunicorn/MCP local sockets
Shared Memory (shm_open + mmap)Maps identical physical RAM pages cleanly into multiple PIDsZero copy (nanosecond reads for multi-GB tensors!)Zero built-in sync (requires futex/semaphore + careful SIGBUS size checks)

Watch out closely for Zombie process (Z) hygiene: once a child finishes exit(), the kernel immediately frees 100% of its virtual RAM, heap, and sockets cleanly except one small task_struct slot preserving its PID and exit code until the parent checks waitpid(). If a broken parent worker forgets to reap dead subprocesses, Z entries pile up silently until hitting pid_max / container pids.max limits (fork: Resource temporarily unavailable!).

c
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
​
int spawn_and_reap_worker(char *const argv[]) {
pid_t pid = fork();
if (pid < 0) return -1;
​
if (pid == 0) {
/* Child process: close unneeded parent FDs (or rely on O_CLOEXEC) then overlay binary cleanly */
execv(argv[0], argv);
_exit(127); /* Always use _exit() on exec failure so child doesn't flush parent stdio twice! */
}
​
int status = 0;
/* Reap exit status deterministically so child PID never leaks as a kernel Zombie (Z) */
while (waitpid(pid, &status, 0) < 0) {
continue;
}
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

Trade-offs

Unix Domain Sockets (AF_UNIX) simplify local microservices (Nginx -> FastAPI -> Postgres) dramatically cleanly with filesystem ACL permissions, natural message framing (SOCK_SEQPACKET), zero manual mutex locking, and safe graceful disconnects cleanly. Reaching cleanly down to POSIX shared memory (mmap / /dev/shm) unlocks genuine zero-copy multi-gigabyte tensor exchanges across co-located Python/C++ AI workers cleanly—yet introduces explicit semaphore synchronization, fixed /dev/shm container size caps (Docker defaults to tiny 64MB /dev/shm!), and stale crash cleanup complexity cleanly.

Failure modes and misconceptions

  • Trying kill -9 on <defunct> Zombie Processes: Zombies are already dead; signals bounce off uselessly cleanly! Only calling waitpid() inside the parent PID (or killing a stuck zombie-spawning parent so PID 1 adopts & reaps them cleanly) clears Z rows cleanly.
  • Docker Default 64 MB /dev/shm Crash: Launching multi-worker PyTorch tensor shared-memory pipelines cleanly inside default containers crashes immediately with Bus error (core dumped) or insufficient shared memory unless configured with --shm-size=4g / emptyDir: medium: Memory!
  • Calling exit() Instead of _exit() After Failed fork()/execve(): Calling standard exit() in a forked child flushes buffered parent stdio streams twice, duplicating output log lines cleanly.
  • Pipe Deadlocks on Unread stdout + stderr: Spawning child CLIs via pipes (subprocess.Popen) then calling wait() before draining pipes stalls cleanly permanently once a 64 KB OS pipe fills cleanly (use communicate()!).

Decision scenario

A containerized AI worker pool connects to a local C++ reranking daemon cleanly across 127.0.0.1:8080 while PyTorch batch loaders intermittently throw SIGBUS crashes cleanly and leftover git helper subprocesses stack up in Z state inside Kubernetes. Switch daemon communication cleanly onto an AF_UNIX socket with O_CLOEXEC, mount a sized Kubernetes Memory emptyDir over /dev/shm (4Gi), and run container PID 1 via tini + explicit waitpid loops cleanly.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next