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:
\( \mathbf{fork()} \longrightarrow \mathbf{execve()} \longrightarrow \mathbf{exit()} / \mathbf{\_exit()} \longrightarrow \mathbf{waitpid()} \)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:
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.
#include <unistd.h>
pid_t fork(void);- Return Value:
- Child process:
0 - Parent process:
PIDof the newly created child (positive integer) - Failure:
-1(errnoset)
- Child process:
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.
#include <unistd.h>
int execve(const char *pathname, char *const argv[], char *const envp[]);<pathname>: Path to the target executable ($PATHis not searched)<argv>: Argument vector. By conventionargv[0]is the program name; the last element must strictly beNULL<envp>: Environment vector. The last element must beNULL
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) vsv(Vector): Variable arguments list (comma-separated) vs array (char *argv[])p(PATH): Searches$PATHautomatically (allows specifying filename only)e(Environment): Accepts a custom environment array (inherits caller’senvironif omitted)
Signatures#
#include <unistd.h>
// 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 andlibciterate through pointers inargv[]until reachingNULL. Omission causes memory overrun past array bounds. - List (
l): Variadicva_arg()macro requires an explicit sentinel to stop pulling arguments from the call stack. - Cast Requirement (
(char *) NULL): In C,NULLis often defined as integer0. On 64-bit systems wheresizeof(int) == 4andsizeof(void *) == 8, passing uncastNULLto 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#
// 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)#
#include <stdlib.h>
void exit(int status); // C library function (flushes buffers, runs atexit handlers)
#include <unistd.h>
void _exit(int status); // Linux kernel system call (terminates immediately without user cleanup)
exit(): Invokes registeredatexit()exit handlers (similar todeferin 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#
Critical: Calling
exit()instead of_exit()in a child process following anexecvefailure introduces two critical bugs:
- 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.- 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.
5. Monitoring Child Processes: waitpid (TLPI Ch 26)#
Reaps the exit status of terminated child processes to prevent Zombie processes.
#include <sys/wait.h>
pid_t wait(int *wstatus);
pid_t waitpid(pid_t pid, int *wstatus, int options);wait(&status)is equivalent towaitpid(-1, &status, 0).
waitpid Parameters#
<pid>:> 0: Wait specifically for the child with this PID-1: Wait for any terminated child process
<options>:0: Block until a child terminatesWNOHANG: Return immediately with0if 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:
#include <signal.h>
#include <sys/wait.h>
// 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#
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
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;
}