The Complete Guide to Unix Processes: fork, exec, wait and Exit
Learn how Unix processes work in C on Linux: create them with fork, replace them with exec, collect them with wait, and end them cleanly with exit.

Every program you have ever started on a Unix system was started by another program, and every one of them ended with a number that somebody was supposed to read. Four system calls cover that whole life cycle: fork creates a process, exec replaces the program it runs, wait collects the result, and exit produces it. Most process bugs, from zombie processes to a shell that hangs after a pipe, come from misunderstanding one of those four, which is why this guide walks through each of them with code you can compile on Linux.
The examples use C11 compiled with GCC 14 on Linux 6.12 with glibc 2.40. The system call behavior comes from the POSIX.1-2024 specification and the Linux man-pages project, and where Linux differs from POSIX the text says so. If you only want the shortest path to a child process, read the sections on fork, execvp and waitpid and skip the rest until something breaks.
The model in one paragraph
A process is a running program plus the kernel's bookkeeping for it: a process ID, an address space, a table of open file descriptors, a current directory, signal dispositions, and a parent. Unix does not have a call that means "start this program as a new process". It has two smaller calls that you combine. fork makes a near-copy of the caller. execve throws away the program in the current process and loads another one into the same process, keeping the process ID and most of the descriptor table. Splitting creation from loading is the reason a shell can redirect output before starting a command: between the two calls the child can rearrange its own descriptors, and the new program never knows.
The rest of the model is the parent's side. When a child ends, the kernel keeps a small record of how it ended until the parent asks for it with wait. That record is the exit status, and a child whose record nobody has collected is a zombie. A child whose parent ended first is an orphan and gets a new parent. Those two words cover most of what goes wrong.
Your first fork
fork returns twice. In the parent it returns the child's process ID, in the child it returns 0, and on failure it returns -1 in the parent and no child exists. Everything else about the call follows from that return value.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
printf("child: pid=%d parent=%d\n", (int)getpid(), (int)getppid());
_exit(7);
}
int status;
if (waitpid(pid, &status, 0) < 0) {
perror("waitpid");
return EXIT_FAILURE;
}
printf("parent: pid=%d child=%d exited with %d\n",
(int)getpid(), (int)pid, WEXITSTATUS(status));
return EXIT_SUCCESS;
}Build it with gcc -std=c11 -Wall -Wextra -o fork_basic fork_basic.c. The process IDs differ on every run, but the shape of the output is fixed because the parent blocks in waitpid until the child has printed and ended:
child: pid=48211 parent=48210
parent: pid=48210 child=48211 exited with 7Two details in that program matter. The child ends with _exit(7) rather than return, so it never runs the cleanup code that belongs to the parent's copy of the program, a point the exit section covers in full. And the parent checks both calls for failure, because fork really can fail: EAGAIN when a process or thread limit is reached, ENOMEM when the kernel cannot allocate what the child needs.
What the child inherits
The child starts as a copy of the parent at the moment of the call. It gets its own copy of the memory, so a variable the child changes is not changed in the parent. It gets a copy of the descriptor table, and that copy is the surprise: both tables point at the same open file descriptions, which means the file offset is shared.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int fd = open("shared.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
perror("open");
return EXIT_FAILURE;
}
int counter = 1;
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
counter = 99;
write(fd, "child\n", 6);
_exit(0);
}
waitpid(pid, NULL, 0);
write(fd, "parent\n", 7);
printf("parent counter is still %d\n", counter);
close(fd);
return EXIT_SUCCESS;
}After the child writes six bytes, the shared offset sits at 6, so the parent's write lands after them instead of overwriting them. The file ends up holding both lines in order:
parent counter is still 1child
parentThe first block is what the program prints; the second is the content of shared.txt. If the parent and child each opened the file separately they would have two offsets and would overwrite each other. Sharing is the point of inheriting the descriptor, and it is how a shell hands the same terminal to a pipeline. The full list of what is and is not inherited, including the pending signals that are cleared and the memory locks that are not copied, is in the "Description" section of the fork(2) man page.
Linux does not copy the memory eagerly. Parent and child share the same physical pages, marked read-only, and the kernel copies a page only when one side writes to it. That copy-on-write design is why a fork of a large process is not as slow as the size suggests, and a later post in this series covers it in depth.
Replacing the program with exec
fork alone gives you two copies of the same program. To run a different program, the child calls one of the exec functions, which replace the current program with a new one. The process ID stays, the open descriptors stay unless they are marked close-on-exec, and everything else (the code, the stack, the heap, the mappings) is gone. A successful exec never returns, because the code that would receive the return value no longer exists.
The family differs only in how you pass the arguments and where the program is found. The letters in the name tell you:
| Function | Arguments passed as | Searches PATH | Environment |
|---|---|---|---|
execl | list | no | inherited |
execlp | list | yes | inherited |
execle | list | no | explicit envp |
execv | array | no | inherited |
execvp | array | yes | inherited |
execve | array | no | explicit envp |
execve is the system call. The rest are library wrappers in glibc. For most work execvp is the right one: it takes an array, so you can build the argument list at run time, and it searches PATH the way a shell does.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
char *argv[] = { "ls", "-1", "/usr/include/sys/wait.h", NULL };
execvp(argv[0], argv);
perror("execvp");
_exit(127);
}
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status))
printf("ls exited with %d\n", WEXITSTATUS(status));
return EXIT_SUCCESS;
}/usr/include/sys/wait.h
ls exited with 0The line after execvp only runs when the call failed, so it is the error path and nothing else. The child reports the error with perror and leaves with status 127, the number shells use for "command not found". Note that argv[0] is a convention, not a rule: the kernel passes whatever you give it, and programs such as BusyBox read argv[0] to decide which tool to behave as. The array must end in a null pointer, and forgetting that terminator is the classic exec bug that sends the new program reading past the end of its own argument list.
If the program does not exist, execvp returns -1 with errno set to ENOENT. If it exists but the process lacks execute permission, errno is EACCES. Both come back only to the child, which is why the next section's problem exists: the parent cannot tell a failed exec from a program that ran and failed, unless the child reports it.
Waiting and decoding the status
waitpid blocks until a child changes state and then fills in an integer that packs several facts together. You never read that integer directly; you ask it questions with macros defined in <sys/wait.h>.
| Macro | True when | Companion |
|---|---|---|
WIFEXITED(s) | child called exit or returned from main | WEXITSTATUS(s) gives the low 8 bits |
WIFSIGNALED(s) | a signal killed the child | WTERMSIG(s) gives the signal number |
WIFSTOPPED(s) | child stopped, with WUNTRACED | WSTOPSIG(s) gives the signal |
WIFCONTINUED(s) | child resumed, with WCONTINUED | none |
Only the low eight bits of an exit code survive, so exit(256) looks like exit(0) to the parent. A shell reports a signal death as 128 plus the signal number, which is a shell convention and not something the kernel stores.
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
static void report(pid_t pid)
{
int status;
if (waitpid(pid, &status, 0) < 0) {
perror("waitpid");
return;
}
if (WIFEXITED(status))
printf("%d exited, code %d\n", (int)pid, WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("%d killed by signal %d\n", (int)pid, WTERMSIG(status));
}
int main(void)
{
pid_t a = fork();
if (a == 0)
_exit(3);
pid_t b = fork();
if (b == 0) {
raise(SIGTERM);
_exit(0);
}
report(a);
report(b);
return EXIT_SUCCESS;
}2514 exited, code 3
2515 killed by signal 15The second child raises SIGTERM against itself, whose default action ends the process, so the _exit(0) after it never runs. Signal 15 is SIGTERM on Linux. The process IDs will differ on your machine.
waitpid(-1, ...) waits for any child, and the option WNOHANG turns the call into a poll that returns 0 when nothing has finished yet. A loop that calls waitpid(-1, &status, WNOHANG) until it returns something other than a positive value is the standard way to reap every child that has already finished.
Four ways a process ends
A process ends in one of four ways, and the differences decide whether your buffered output reaches the file.
| Way out | Runs atexit handlers | Flushes stdio | Status seen by the parent |
|---|---|---|---|
return n from main | yes | yes | n |
exit(n) | yes | yes | n |
_exit(n) | no | no | n |
| killed by a signal | no | no | signal number |
exit runs the functions registered with atexit, flushes and closes every stdio stream, removes files created with tmpfile, and then calls _exit. That is what you want in the parent. It is usually the opposite of what you want in a forked child, because the child's copy of the stdio buffers still holds whatever the parent had written but not yet flushed. If the child calls exit, that data is written a second time.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
printf("before fork");
pid_t pid = fork();
if (pid == 0) {
printf(" (child)\n");
exit(0);
}
waitpid(pid, NULL, 0);
printf(" (parent)\n");
return EXIT_SUCCESS;
}When standard output is a terminal, stdio is line-buffered and the text before the fork is still in the buffer because no newline has been printed. Redirect the output to a file or a pipe and it becomes fully buffered, with the same result. Both processes then flush the same pending text:
before fork (child)
before fork (parent)The cure has two parts. Flush before you fork, with fflush(NULL) to flush every open output stream, and call _exit in a child that is not going to exec anything. The post on flushing stdio buffers before fork and exec in this series covers the buffering rules in detail.
Zombies, orphans and reaping
When a child ends, the kernel frees its memory and descriptors but keeps its process-table entry, holding the exit status and resource usage, until the parent collects it. A child in that state shows as Z in ps and is called a zombie. It uses no CPU and almost no memory, but it holds a process ID, and a parent that forks in a loop without waiting will eventually hit the process limit.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid == 0)
_exit(0);
printf("child %d has exited; sleeping 30 seconds\n", (int)pid);
sleep(30);
return EXIT_SUCCESS;
}While it sleeps, ps -o pid,ppid,stat,comm --ppid <parent pid> shows the dead child still listed:
child 5120 has exited; sleeping 30 seconds PID PPID STAT COMMAND
5120 5119 Z make_zombie <defunct>The state column reads Z and the command carries <defunct>. The fix is for the parent to call wait or waitpid, or to arrange for the kernel to reap automatically (covered below).
An orphan is the reverse situation. If the parent ends while the child still runs, the kernel reparents the child to process 1, or to the nearest ancestor that declared itself a subreaper with prctl(PR_SET_CHILD_SUBREAPER). The new parent is expected to reap the child when it ends, and init does. An orphan is therefore harmless by itself; what you lose is the link to your own children, so a daemon that wants to stay in charge of its descendants has to stay alive or become a subreaper.
Reaping automatically with SIGCHLD
A parent that cannot block in waitpid can let the kernel tell it. Whenever a child ends or stops, the parent receives SIGCHLD. The default action ignores the signal, which is why unreaped zombies pile up silently. A handler that reaps in a loop fixes it:
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
static void on_sigchld(int sig)
{
(void)sig;
int saved = errno;
while (waitpid(-1, NULL, WNOHANG) > 0)
;
errno = saved;
}
int main(void)
{
struct sigaction sa = {0};
sa.sa_handler = on_sigchld;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(SIGCHLD, &sa, NULL) < 0) {
perror("sigaction");
return EXIT_FAILURE;
}
for (int i = 0; i < 3; i++) {
if (fork() == 0)
_exit(i);
}
sleep(1);
puts("all children reaped");
return EXIT_SUCCESS;
}all children reapedThe loop is not optional. Standard signals do not queue, so three children ending at once can deliver a single SIGCHLD, and a handler that reaps only one leaves two zombies behind. WNOHANG stops the loop when nothing is left, SA_RESTART keeps a slow system call in the main program from failing with EINTR, and saving errno keeps the handler from corrupting an error code the interrupted code was about to read. If you only need the zombies gone and do not care about the status, setting the disposition of SIGCHLD to SIG_IGN or setting SA_NOCLDWAIT makes the kernel discard the records itself, at the price that waitpid then fails with ECHILD once all children are gone.
Wiring two processes together with a pipe
A pipe is a kernel buffer with a read end and a write end, created by pipe. Because descriptors survive fork and exec, one process can write into one end while a child reads from the other. Add dup2 to point a child's standard input or output at a pipe end, and you have what a shell does for ls | wc -l.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int fds[2];
if (pipe(fds) < 0) {
perror("pipe");
return EXIT_FAILURE;
}
pid_t left = fork();
if (left == 0) {
dup2(fds[1], STDOUT_FILENO);
close(fds[0]);
close(fds[1]);
char *argv[] = { "printf", "alpha\nbeta\ngamma\n", NULL };
execvp(argv[0], argv);
_exit(127);
}
pid_t right = fork();
if (right == 0) {
dup2(fds[0], STDIN_FILENO);
close(fds[0]);
close(fds[1]);
char *argv[] = { "wc", "-l", NULL };
execvp(argv[0], argv);
_exit(127);
}
close(fds[0]);
close(fds[1]);
waitpid(left, NULL, 0);
waitpid(right, NULL, 0);
return EXIT_SUCCESS;
}3Count the close calls, because they are what makes this work. Each child closes both original pipe ends after dup2 has copied the one it needs onto standard input or output. The parent closes both of its copies too. If any process keeps the write end open, wc never sees end of file and waits forever, which is the standard reason a hand-built pipeline hangs. The reader sees end of file only when every descriptor referring to the write end is closed.
Close-on-exec and leaked descriptors
An exec keeps every open descriptor unless it carries the close-on-exec flag, and that default is the source of a quiet class of bugs: a child program inherits a database socket or a lock file it has no business holding. Open files with O_CLOEXEC, or set FD_CLOEXEC with fcntl, so only the descriptors you deliberately dup2 onto 0, 1 and 2 survive.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int leaked = open("/etc/hostname", O_RDONLY);
int kept = open("/etc/hostname", O_RDONLY | O_CLOEXEC);
printf("leaked fd=%d, close-on-exec fd=%d\n", leaked, kept);
fflush(stdout);
pid_t pid = fork();
if (pid == 0) {
char *argv[] = { "ls", "-l", "/proc/self/fd", NULL };
execvp(argv[0], argv);
_exit(127);
}
waitpid(pid, NULL, 0);
return EXIT_SUCCESS;
}leaked fd=3, close-on-exec fd=4
total 0
lrwx------ 1 user user 64 Nov 23 10:02 0 -> /dev/pts/0
lrwx------ 1 user user 64 Nov 23 10:02 1 -> /dev/pts/0
lrwx------ 1 user user 64 Nov 23 10:02 2 -> /dev/pts/0
lr-x------ 1 user user 64 Nov 23 10:02 3 -> /etc/hostname
lr-x------ 1 user user 64 Nov 23 10:02 4 -> /proc/NNNN/fdThe ls listing shows descriptor 3, the leaked file, but not descriptor 4, which exec closed. The entry for 4 that you do see is the directory handle ls itself opened to read /proc/self/fd. User names, dates and the process ID in the last line will differ on your machine. Descriptor 3 in the listing is the case to remember: any program you exec can read it, write to it and pass it on.
A shell in thirty lines
Everything so far fits into a program that reads a line, splits it into words, forks, executes and waits. That is the core of every Unix shell, and writing it once explains why cd has to be built in.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
char line[1024];
for (;;) {
fputs("tinysh> ", stdout);
fflush(stdout);
if (!fgets(line, sizeof line, stdin))
break;
char *argv[64];
int argc = 0;
for (char *tok = strtok(line, " \t\n"); tok && argc < 63;
tok = strtok(NULL, " \t\n"))
argv[argc++] = tok;
argv[argc] = NULL;
if (argc == 0)
continue;
if (strcmp(argv[0], "cd") == 0) {
if (argc < 2 || chdir(argv[1]) < 0)
perror("cd");
continue;
}
if (strcmp(argv[0], "exit") == 0)
break;
pid_t pid = fork();
if (pid < 0) {
perror("fork");
continue;
}
if (pid == 0) {
execvp(argv[0], argv);
perror(argv[0]);
_exit(127);
}
int status;
waitpid(pid, &status, 0);
}
return EXIT_SUCCESS;
}A session looks like this, with the commands you type after the prompt:
tinysh> echo hello
hello
tinysh> nosuchprogram
nosuchprogram: No such file or directory
tinysh> exitcd is a built-in for a reason that falls straight out of the process model. The working directory belongs to a process, so a forked child that calls chdir changes only its own directory and then ends, leaving the shell where it was. Any command that must change the shell's own state, such as cd, exit or export, has to run inside the shell process, not in a child. The nosuchprogram line is the failed-exec path from earlier: the child prints the error and exits with 127, and the shell moves on.
Telling a failed exec from a failed program
The parent cannot tell exit code 127 from exec failure from a program that chose to exit 127. A reliable fix uses the close-on-exec flag on a pipe. The child writes its errno into the pipe if execvp returns; if execvp succeeds, the pipe closes automatically and the parent reads zero bytes.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int fds[2];
if (pipe2(fds, O_CLOEXEC) < 0) {
perror("pipe2");
return EXIT_FAILURE;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
char *argv[] = { "no-such-tool", NULL };
execvp(argv[0], argv);
int err = errno;
write(fds[1], &err, sizeof err);
_exit(127);
}
close(fds[1]);
int err = 0;
ssize_t n = read(fds[0], &err, sizeof err);
close(fds[0]);
waitpid(pid, NULL, 0);
if (n == (ssize_t)sizeof err)
printf("exec failed: %s\n", strerror(err));
else
printf("exec succeeded\n");
return EXIT_SUCCESS;
}exec failed: No such file or directorypipe2 with O_CLOEXEC is a Linux call that glibc also exposes; POSIX.1-2024 added it to the standard. The trick works because the write end vanishes at the moment of a successful exec, so the parent's read returns zero. Language runtimes use the same idea internally, and the next sections show it hidden inside std::process::Command and os/exec.
posix_spawn when fork is the wrong tool
fork copies the page tables of the whole process, and a program with a very large address space pays for that on every launch. When all you want is "start this program with these redirections", posix_spawn expresses the same intent in one call, and glibc implements it with clone using CLONE_VM and CLONE_VFORK so it avoids the copy.
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
extern char **environ;
int main(void)
{
pid_t pid;
char *argv[] = { "echo", "spawned", NULL };
int rc = posix_spawnp(&pid, "echo", NULL, NULL, argv, environ);
if (rc != 0) {
fprintf(stderr, "posix_spawnp failed: %d\n", rc);
return EXIT_FAILURE;
}
int status;
waitpid(pid, &status, 0);
printf("exit code %d\n", WEXITSTATUS(status));
return EXIT_SUCCESS;
}spawned
exit code 0Note that posix_spawnp reports errors through its return value, not errno, and a missing program is reported to the caller directly, with no 127 to decode. For redirection you add actions to a posix_spawn_file_actions_t object. The trade-off is flexibility: anything you would do between fork and exec that the spawn attributes cannot express forces you back to fork. A later post in this series compares fork, vfork, posix_spawn and clone side by side.
Threads and fork do not mix well
In a multithreaded program, fork creates a child with exactly one thread, the one that called it. The other threads vanish without running any cleanup, and any mutex one of them held stays locked forever in the child. The classic victim is malloc: if another thread was inside the allocator when you forked, the child's first malloc can deadlock.
POSIX therefore restricts the child of a multithreaded program to async-signal-safe functions until it calls exec. In practice that means: fork, then immediately set up descriptors with dup2 and close, then exec or _exit, and do nothing that allocates memory in between. If you need more than that, use posix_spawn, or fork before you start any threads. The expert-level post on why fork is dangerous in multithreaded programs in this series goes through the mechanism and the pthread_atfork hooks.
Seeing processes from the outside
Everything the kernel knows about a process is visible under /proc/<pid>. You do not need a debugger to answer "what is this process waiting for". Three files cover most questions: status for the state and the parent, cmdline for the arguments with null separators, and fd/ for the open descriptors.
grep -E '^(Name|State|PPid|Threads):' /proc/self/statusName: grep
State: R (running)
PPid: 31877
Threads: 1The state letter is the one to learn: R running, S sleeping, D uninterruptible sleep, Z zombie, T stopped. A child that shows Z is waiting for you to call wait. Output values here will differ on your machine; the parent ID is whatever shell ran the command.
The same life cycle in Rust and Go
Higher-level runtimes wrap these calls and hide the sharp edges. Rust's std::process::Command calls posix_spawn where it can and falls back to fork and exec when it needs features such as changing the user, and it reports a failed exec through exactly the close-on-exec pipe trick above. Go's os/exec goes through syscall.ForkExec, which does the same.
use std::process::Command;
fn main() {
let status = Command::new("echo")
.arg("from rust")
.status()
.expect("failed to start echo");
println!("exit code: {:?}", status.code());
}from rust
exit code: Some(0)The Option in code() is the WIFEXITED check in disguise: it is None when a signal killed the child. Dropping a Child without calling wait in Rust does not reap it, so the zombie rules apply there too. The dedicated posts on std::process::Command and os/exec in this series cover the details.
Common failures and what causes them
| Symptom | Likely cause | Fix |
|---|---|---|
| Output appears twice | unflushed stdio buffer copied by fork | fflush(NULL) before fork, _exit in the child |
ps shows <defunct> | parent never called wait | reap with waitpid, or handle SIGCHLD |
fork: Resource temporarily unavailable | process or thread limit reached | find the leak, check ulimit -u |
| Pipeline hangs after the last line | a write end of the pipe is still open somewhere | close every unused pipe end in every process |
| Child starts with extra open files | descriptors not marked close-on-exec | use O_CLOEXEC when opening |
exec "succeeds" but nothing runs | argv missing the NULL terminator or wrong argv[0] | end the array with NULL |
| Exit code is always 0 or odd | status not decoded, or code over 255 | use WIFEXITED and WEXITSTATUS, keep codes below 256 |
Most of these are covered by one habit: after every fork, ask what the child holds that it should not, and what the parent still needs to do for it.
Controlling the environment with execve
The p and plain variants of exec hand the child your current environment. The e variants let you replace it, which is how you run a program in a controlled setting: a build step that must not see your credentials, a test that needs a fixed locale, a service launched with exactly the variables it documents.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
char *argv[] = { "/usr/bin/env", NULL };
char *envp[] = { "LANG=C", "GREETING=hello", NULL };
execve(argv[0], argv, envp);
perror("execve");
_exit(127);
}
waitpid(pid, NULL, 0);
return EXIT_SUCCESS;
}LANG=C
GREETING=helloexecve does not search PATH, so the program is named by its full path. The envp array is a list of NAME=value strings ending in a null pointer, and the order in which env prints them is the order you wrote them. Because the child sees only those two variables, there is no PATH and no HOME in its world. That is exactly the point, and also the first thing that breaks when a program you launch this way tries to find another one.
The same idea works for the other half of the inheritance question. Resource limits set with setrlimit are inherited across fork and kept across exec, so a parent can lower the limits for a child before it starts, for instance capping the address space at a figure you choose, without the child's cooperation. The same is true for the umask, the current directory, the signal mask and the ignored signals. Handled signals are the exception: a function address means nothing in a new program, so exec resets every signal that had a handler back to its default action. Ignored signals stay ignored, which is the origin of the old trap where a program started with SIGPIPE ignored behaves differently in a shell script than at a terminal.
Process groups, sessions and the terminal
Processes belong to a process group, and groups belong to a session. A shell puts each pipeline in its own group so that pressing Ctrl+C at the terminal can send SIGINT to every process of the foreground job and to nothing else. The terminal driver sends the signal to the foreground group, not to a single process.
A child starts in its parent's group. To put it in a new one, the shell calls setpgid in both the parent and the child, because either might run first and whichever goes first would otherwise leave the child in the old group for a moment.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
setpgid(0, 0);
printf("child pid=%d pgid=%d\n", (int)getpid(), (int)getpgid(0));
_exit(0);
}
setpgid(pid, pid);
waitpid(pid, NULL, 0);
printf("parent pid=%d pgid=%d\n", (int)getpid(), (int)getpgid(0));
return EXIT_SUCCESS;
}child pid=7301 pgid=7301
parent pid=7300 pgid=7300The child's group ID equals its own process ID, which makes it the leader of a new group, and the parent stays in a group of its own: when a program is launched from a shell, the parent's group ID is the shell's job. The numbers vary from run to run. Both setpgid calls are legal even though one of them may fail harmlessly; the call in the parent can return EACCES if the child has already called exec, and the call in the child is then the one that took effect.
A session is the next level up. setsid makes the caller the leader of a new session with no controlling terminal, which is the first step of turning a program into a daemon. A daemon in the classic recipe forks, lets the parent exit, calls setsid in the child, forks again so the survivor can never reacquire a terminal, changes directory to /, resets umask and closes the standard descriptors. Modern service managers make most of that unnecessary, because they start your program already detached, but the recipe is a good test of whether you understand the model.
Resource usage of a finished child
wait returns more than the exit status. The wait4 call, a BSD interface that Linux provides, and the POSIX getrusage with RUSAGE_CHILDREN both report the CPU time and memory the child used. This is how time can print what a command cost after the fact.
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
char *argv[] = { "sort", "/usr/share/dict/words", "-o", "/dev/null", NULL };
execvp(argv[0], argv);
_exit(127);
}
int status;
struct rusage ru;
if (wait4(pid, &status, 0, &ru) < 0) {
perror("wait4");
return EXIT_FAILURE;
}
printf("user %ld.%06ld s, system %ld.%06ld s, max RSS %ld KiB\n",
(long)ru.ru_utime.tv_sec, (long)ru.ru_utime.tv_usec,
(long)ru.ru_stime.tv_sec, (long)ru.ru_stime.tv_usec,
ru.ru_maxrss);
return EXIT_SUCCESS;
}user 0.182311 s, system 0.021774 s, max RSS 9632 KiBThe figures printed here are an example of the format only; they depend on the machine and the file, so your numbers will differ. On Linux ru_maxrss is in kilobytes, while macOS reports bytes, a difference that has broken more than one portable timing tool. The child's usage becomes available only when you wait for it, which is another reason an unreaped child is a leak of information as well as of a table slot.
Following a process with strace
When a launch misbehaves, the fastest way to see the calls is to watch them. strace -f follows children across fork, and the output reads like the model in this guide.
strace -f -e trace=execve,clone,wait4,exit_group sh -c 'ls /nonexistent'execve("/usr/bin/sh", ["sh", "-c", "ls /nonexistent"], 0x7ffd1c1e0f48 /* 38 vars */) = 0
clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f2c1e9cba10) = 9120
[pid 9120] execve("/usr/bin/ls", ["ls", "/nonexistent"], 0x55d0c4a0b6e0 /* 38 vars */) = 0
[pid 9120] exit_group(2) = ?
[pid 9120] +++ exited with 2 +++
wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 2}], 0, NULL) = 9120
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=9120, si_uid=1000, si_status=2, si_utime=0, si_stime=0} ---
exit_group(2) = ?
+++ exited with 2 +++Several things in that trace are worth knowing. On Linux, glibc implements fork with the clone system call, so you see clone and not fork. The exec happens in the child, whose process ID is shown in brackets. The child ends with exit_group, which ends every thread of a process, and the parent receives SIGCHLD with the status inside the siginfo structure. The 2 is the status ls uses for a serious error. The addresses, the variable count and the process IDs will differ on your machine. Reading a trace like this is the quickest way to find out which of your children failed to exec, and which one is still holding a pipe open.
Reading the exit code in a script
The bridge between C and shell is the exit status. A shell stores the status of the last command in $?, and a signal death appears as 128 plus the signal number, so a child killed by SIGSEGV (signal 11) reads as 139. That mapping is a shell convention. Your C parent gets the real facts from WIFSIGNALED and WTERMSIG, and it should keep them separate when it logs a failure, because "exit code 139" and "killed by signal 11" send a debugging session in different directions.
If you write a program that others will call from scripts, follow the conventions: 0 for success, 1 for a general failure, 2 for a usage error, 126 for found but not executable, 127 for not found, and nothing above 125 for your own meaning. That keeps your codes from colliding with the ones a shell invents.
A pattern for running a command and capturing its output
Most real programs do not just wait for a child; they want what it printed. The pipeline example generalizes into a helper that runs a command and returns its standard output as a string. The one thing to get right is the order: read until end of file first, then wait.
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int fds[2];
if (pipe(fds) < 0) {
perror("pipe");
return EXIT_FAILURE;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
dup2(fds[1], STDOUT_FILENO);
close(fds[0]);
close(fds[1]);
char *argv[] = { "uname", "-s", NULL };
execvp(argv[0], argv);
_exit(127);
}
close(fds[1]);
char buf[256];
ssize_t n, total = 0;
while ((n = read(fds[0], buf + total, sizeof buf - 1 - (size_t)total)) > 0)
total += n;
buf[total] = '\0';
close(fds[0]);
int status;
waitpid(pid, &status, 0);
printf("captured %zd bytes: %s", total, buf);
printf("exit code %d\n", WEXITSTATUS(status));
return EXIT_SUCCESS;
}captured 6 bytes: Linux
exit code 0If the parent called waitpid before reading, a child that writes more than the pipe holds, 64 KiB by default on Linux, would block on write while the parent blocks on waitpid, and the two would wait for each other forever. Reading to the end first removes the cycle. The parent also closes its copy of the write end before it reads. If it did not, it would be a writer itself and the loop would never see end of file. A real helper also handles standard error, which needs a second pipe or a dup2 onto the same one, and uses poll to drain both without blocking on either.
Limits that stop you from forking
A process cannot fork without bound. Two limits matter. RLIMIT_NPROC caps the number of processes a user may own, and the system-wide ceilings in /proc/sys/kernel/pid_max and /proc/sys/kernel/threads-max cap the whole machine. When fork fails with EAGAIN, one of them has been reached, and the useful question is who owns all those processes, not how to raise the limit.
ulimit -u
cat /proc/sys/kernel/pid_max
ps -u "$USER" -o stat= | sort | uniq -c63218
4194304
3 R
41 S
1 ZThe first number is the per-user limit from the shell, the second is the kernel ceiling, and the table counts your processes by state. All three values depend on the machine. A user with thousands of Z entries has a parent that never reaps, and the fix is in that parent. A user with thousands of S entries has a program that forks without bound, usually because a respawn loop restarts a child that fails at once.
The failing-fork case also teaches the discipline for handling it. Never ignore the -1. A program that carries on after a failed fork treats the parent's own return value of -1 as a child's process ID, and a later call such as kill(-1, SIGTERM) or waitpid(-1, ...) with that value does something very different from what was intended. The first sends a signal to every process the caller may signal, and the second waits for any child. Checking the return value costs three lines and removes a whole category of production incident.
Habits that keep process code correct
Process code is short, and short code hides its failures. Four habits catch most of them.
First, draw the family tree before you write the code. Write down which process holds which descriptors after each call, and cross out the ones that must be closed. Most pipeline hangs are visible on that drawing.
Second, give every child exactly one of two endings: it calls exec, or it calls _exit. A child that falls out of the if (pid == 0) block and continues into the parent's code is the origin of programs that run their main loop twice, and of the output that appears in duplicate.
Third, decide who reaps each child at the moment you create it. If the answer is "whoever calls waitpid in this function", the code is simple. If the answer is "the SIGCHLD handler", then the handler must loop, and the main code must not also call wait for a particular child unless it blocks the signal first, or the handler will take the status the main code was waiting for.
Fourth, treat the exit status as part of the interface. A program that returns the wrong code makes every script that calls it wrong in a way that no log line explains.
Where this model stops working
This guide is about Linux and POSIX systems. Windows has no fork; its CreateProcess call is closer to posix_spawn, and portable code that uses fork will not build there. On macOS the calls exist, but the system frameworks are not safe to use in a forked child that has not called exec, so spawning is the better route there too.
Programs that start thousands of short-lived children per second, such as build systems and web servers, should look at posix_spawn, vfork or clone3 instead of a plain fork, and at a persistent worker pool instead of a process per request. Programs that need to be notified when a child exits inside an event loop should use a pidfd rather than SIGCHLD. And if you only want to run a shell pipeline from C and do not need to manage the pieces, popen and system exist, with the warning that passing unchecked input to system hands a shell to whoever controls the input.


