Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ Based on *The Linux Programming Interface* Chapter 6 (Processes), Chapter 24 (Process Creation), Chapter 25 (Process Termination), Chapter 26 (Monitoring Child Processes), and Chapter 27 (Program Execution). The Linux process lifecycle is governed by the combination of four core system calls: {{< katex display >}} \mathbf{fork()} \longrightarrow \mathbf{execve()} \longrightarrow \mathbf{exit()} / \mathbf{\_exit()} \longrightarrow \mathbf{waitpid()} {{< /katex >}} --- ## 1. Process Virtual Memory Layout (TLPI Ch 6) The kernel allocates an independent virtual address space for each process, structured from low to high addresses as follows: ```text High Address (0x7FFF...) ┌──────────────────────────────────────────────┐ │ Kernel Space (Inaccessible from user space) │ ├──────────────────────────────────────────────┤ │ Environment (environ) and Arguments (argv) │ ├──────────────────────────────────────────────┤ │ User Stack ▼ (Grows downward) │ Local variables, stack frames │ │ │ │ │ User Heap ▲ (Grows upward) │ malloc() / free() dynamic allocation ├──────────────────────────────────────────────┤ │ BSS Segment │ Uninitialized global/static variables (zeroed) ├──────────────────────────────────────────────┤ │ Data Segment │ Explicitly initialized global/static variables ├──────────────────────────────────────────────┤ │ Text Segment (Machine Code) │ Compiled binary instructions (read-only) └──────────────────────────────────────────────┘ Low Address (0x0000...) ``` --- ## 2. Process Creation: `fork` (TLPI Ch 24) Creates a new child process by duplicating the calling process. ```c #include pid_t fork(void); ``` - **Return Value:** - **Child process:** `0` - **Parent process:** `PID` of the newly created child (positive integer) - **Failure:** `-1` (`errno` set) ### Cloning and Inheritance Semantics - **Copy-on-Write (COW):** `fork()` does not immediately duplicate physical memory. Parent and child share read-only 4KB pages until either process writes to a page, at which point the kernel duplicates that specific page. - **FD Table Inheritance:** The child inherits an exact duplicate of the parent's file descriptor table. Shared descriptors point to the same kernel Open File Descriptions, meaning **file offsets are shared in real time**. - **Not Inherited:** PID (`getpid()`), parent PID (`getppid()`), pending signals, and process CPU execution timers (reset to zero). --- ## 3. Program Execution: `execve` & Family (TLPI Ch 27) Replaces the current process virtual memory (Text, Data, Heap, Stack) with a new executable binary while preserving its PID and open file descriptors. On success, it never returns to the calling code. ### 1. Kernel System Call: `execve(2)` The sole underlying entry point into the kernel for process replacement. All library wrappers eventually translate arguments and invoke `execve`. ```c #include int execve(const char *pathname, char *const argv[], char *const envp[]); ``` - ``: Path to the target executable (`$PATH` is not searched) - ``: Argument vector. By convention `argv[0]` is the program name; **the last element must strictly be `NULL`** - ``: Environment vector. The last element must be `NULL` ### 2. C Library Wrappers: `exec(3)` Family Front-end wrappers provided by `libc`. All functions in this family prepare arguments and invoke `execve(2)`. #### Naming Conventions - **`l` (List)** vs **`v` (Vector)**: Variable arguments list (comma-separated) vs array (`char *argv[]`) - **`p` (PATH)**: Searches `$PATH` automatically (allows specifying filename only) - **`e` (Environment)**: Accepts a custom environment array (inherits caller's `environ` if omitted) #### Signatures ```c #include // Vector variants (array input) int execv(const char *pathname, char *const argv[]); int execvp(const char *file, char *const argv[]); int execvpe(const char *file, char *const argv[], char *const envp[]); // List variants (variadic input) int execl(const char *pathname, const char *arg, ... /*, (char *) NULL */); int execlp(const char *file, const char *arg, ... /*, (char *) NULL */); int execle(const char *pathname, const char *arg, ... /*, (char *) NULL, char *const envp[] */); ``` #### The `NULL` Sentinel Requirement C does not pass array length or variadic argument count metadata: - **Vector (`v`)**: The kernel and `libc` iterate through pointers in `argv[]` until reaching `NULL`. Omission causes memory overrun past array bounds. - **List (`l`)**: Variadic `va_arg()` macro requires an explicit sentinel to stop pulling arguments from the call stack. - **Cast Requirement (`(char *) NULL`)**: In C, `NULL` is often defined as integer `0`. On 64-bit systems where `sizeof(int) == 4` and `sizeof(void *) == 8`, passing uncast `NULL` to variadic functions pushes a 32-bit zero onto the stack, causing stack alignment corruption. Always cast explicitly: `(char *) NULL`. #### Comparison and Typical Use Cases In practice, **`execvp` is the standard choice for shells and command runners** as it combines `$PATH` resolution with dynamic argument arrays. | Function | Arguments | `$PATH` Search | Environment | Typical Use Case | | :--- | :---: | :---: | :---: | :--- | | **`execvp`** | Vector (`v`) | Yes (`p`) | Inherited | **Shell and command runner implementations** | | `execv` | Vector (`v`) | No | Inherited | Fixed binary path with dynamic arguments | | `execvpe` | Vector (`v`) | Yes (`p`) | Custom (`e`) | `$PATH` search with custom environment (GNU extension) | | `execlp` | List (`l`) | Yes (`p`) | Inherited | Hardcoded arguments with `$PATH` search | | `execl` | List (`l`) | No | Inherited | Hardcoded path with hardcoded arguments | | `execle` | List (`l`) | No | Custom (`e`) | Hardcoded arguments with custom environment | #### Usage Examples ```c // 1. Vector pattern (execvp: standard for shells, dynamic argument array) char *args[] = {"ls", "-l", "/usr/include", NULL}; execvp("ls", args); // 2. List pattern (execlp: hardcoded arguments, requires (char *) NULL sentinel) // Note: "ls" is specified twice (1st: program to find in $PATH, 2nd: argv[0] passed to program) execlp("ls", "ls", "-l", "/usr/include", (char *) NULL); // 3. Custom environment pattern (execle: custom environment array follows NULL sentinel) char *env[] = {"TERM=xterm", "LANG=en_US.UTF-8", NULL}; execle("/bin/ls", "ls", "-l", (char *) NULL, env); ``` --- ## 4. Process Termination: `exit` vs `_exit` (TLPI Ch 25) ```c #include void exit(int status); // C library function (flushes buffers, runs atexit handlers) #include void _exit(int status); // Linux kernel system call (terminates immediately without user cleanup) ``` - **`exit()`**: Invokes registered `atexit()` exit handlers (similar to `defer` in Go) in reverse order, flushes and closes all open stdio streams, then terminates. - **`_exit()`**: Bypasses user-space cleanup and immediately invokes the kernel termination procedure. ### Why `_exit()` is Mandatory on `execve` Failure {{% hint danger %}} **Critical:** Calling `exit()` instead of `_exit()` in a child process following an `execve` failure introduces two critical bugs: 1. **Duplicate stdio Output:** Unflushed stdio buffers cloned from the parent during `fork()` are flushed by the child, and then flushed again when the parent terminates, resulting in duplicate output. 2. **Erroneous `atexit()` Handler Execution:** Exit handlers registered by the parent (e.g. deleting temporary lockfiles or closing shared connections) are triggered by the child, disrupting the parent process. Always call `_exit()` or `_Exit()` to bypass user-space cleanup and invoke kernel termination directly without touching parent-owned buffered state or exit handlers. {{% /hint %}} --- ## 5. Monitoring Child Processes: `waitpid` (TLPI Ch 26) Reaps the exit status of terminated child processes to prevent **Zombie processes**. ```c #include pid_t wait(int *wstatus); pid_t waitpid(pid_t pid, int *wstatus, int options); ``` - `wait(&status)` is equivalent to `waitpid(-1, &status, 0)`. ### `waitpid` Parameters - ``: - `> 0`: Wait specifically for the child with this PID - `-1`: Wait for any terminated child process - ``: - `0`: Block until a child terminates - `WNOHANG`: Return immediately with `0` if no child has exited (non-blocking polling) ### Termination Status Macros `wstatus` is a bitfield integer that must be inspected using standard macros: | Macro | Meaning | Value Extraction | | :--- | :--- | :--- | | **`WIFEXITED(wstatus)`** | True if child exited normally (`exit()` or `return`) | **`WEXITSTATUS(wstatus)`**: Exit code (0–255) | | **`WIFSIGNALED(wstatus)`** | True if child was terminated by an unhandled signal | **`WTERMSIG(wstatus)`**: Terminating signal number | ### Asynchronous Zombie Reaping Pattern (`SIGCHLD` + `WNOHANG`) The kernel sends a `SIGCHLD` signal when any child terminates. The parent handles dead children asynchronously without blocking its primary event loop: ```c #include #include // 1. Signal handler invoked upon child termination void sigchld_handler(int sig) { (void)sig; int status; // WNOHANG prevents the handler from blocking if other children are alive while (waitpid(-1, &status, WNOHANG) > 0) { // Zombie reaped successfully } } int main(void) { // 2. Caller registers SIGCHLD handler signal(SIGCHLD, sigchld_handler); // 3. Parent creates children and proceeds with main business logic uninterrupted return 0; } ``` --- ## 6. Canonical Fork-Exec-Wait Pattern ```c #include #include #include #include int main(void) { pid_t pid = fork(); if (pid == -1) { perror("fork failed"); exit(EXIT_FAILURE); } if (pid == 0) { // Child: Execute new program char *args[] = {"ls", "-l", "/usr/include", NULL}; execvp("ls", args); // Reached only if execvp fails perror("execvp failed"); _exit(EXIT_FAILURE); // Prevent stdio buffer double-flush and atexit disruption } // Parent: Wait for child and inspect termination status int status; if (waitpid(pid, &status, 0) == -1) { perror("waitpid failed"); exit(EXIT_FAILURE); } if (WIFEXITED(status)) { printf("Child exited normally with status %d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("Child terminated by signal %d\n", WTERMSIG(status)); } return EXIT_SUCCESS; } ```