Module 2 · Lesson 7 of 30

Processes: fork, exec, wait (mysh v1)

Build mysh v1 while learning process identity, fork, exec, wait, environments, zombies, descriptor inheritance and safe process launching.

  • Beginner to advanced
  • 29 min read
  • 60 min lab
What you will need

Ubuntu 24.04 with gcc, strace and procps (WSL2, VM or container); optional ARM Linux board with a matching toolchain

By the end you can 7 objectives
  • Identify a process and its parent using getpid, getppid and procfs.
  • Explain fork return values, copy-on-write memory and inherited open file descriptions.
  • Choose an exec wrapper and construct terminated argument and environment arrays.
  • Decode child termination and state changes with waitpid and waitid.
  • Implement mysh v1 with built-ins, fork, execvp and checked child collection.
  • Diagnose zombies, descriptor leaks, duplicate buffering and process-limit failures.
  • Evaluate fork, vfork, posix_spawn and shell-based launching for an embedded service.
Read the lesson below; the video will appear here when published.
01

Meet a running program

3 min read

Your mytools executables already read and update files. Now you will build the launcher that runs them. A gives Linux something to schedule, protect and monitor.

Two copies of mywatch can watch different directories. Each has its own variables and open descriptors. A file descriptor is the small integer your program uses to refer to an open resource.

The lets another program refer to it. A namespace is a separate system-resource view. Containers can see different PID numbers from the host.

Use this complete program to print the caller's identity. getpid() returns its PID; getppid() returns its current parent's PID. pid_t is the system's type for these values. The casts match the %jd format without assuming that type's exact representation.

c
#include <inttypes.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    printf("pid=%jd parent=%jd\n",
           (intmax_t)getpid(), (intmax_t)getppid());
    return 0;
}

Save it as identity.c in your lab directory. Compile and run it with these commands:

bash
cc -std=c11 -Wall -Wextra -Wpedantic identity.c -o identity
./identity

The numbers describe this run; the parent is usually your shell. Linux eventually reuses released PID numbers.

Linux exposes process information through procfs, a virtual filesystem normally mounted at /proc. Its files describe kernel state rather than ordinary stored documents. Inspect your shell and the first process using the following commands:

bash
ps -o pid,ppid,stat,comm -p "$$",1
cat /proc/$$/status
readlink /proc/self

In a POSIX shell, $$ expands to the shell's PID. /proc/<pid>/status includes identity, state and memory fields. /proc/self always refers to the process accessing it: here, readlink, rather than the shell. /proc/<pid>/fd lists descriptor links, while /proc/<pid>/cmdline contains arguments separated by zero bytes.

PID 1 is traditionally called init. On a board it might be BusyBox init; on a workstation it might be systemd. It starts or supervises services and must collect adopted children's results. A program running as PID 1 in a container also needs that collection behavior. PID 1 has special Linux signal rules, so ordinary application shutdown assumptions need review there.

A process can exit between listing its procfs directory and opening a file. Permissions can hide information. A saved PID does not permanently identify the same process.

Processes have distinct identitiesInitPID 1 in this namespaceShellParent of the launched toolmywatchDistinct PID and process stateInitPID 1 in this namespaceShellParent of the launched toolmywatchDistinct PID and processstate
A supervisor, a shell and its launched program have distinct identities
02

One call creates two execution paths

4 min read

fork() creates a child from the calling parent. Include <unistd.h> for its declaration. Three return cases determine what your program should do next:

Return value Where you observe it Meaning
-1 Parent only Creation failed; no child exists
0 Child only This is the new execution path
Positive pid_t Parent only This is the new child's PID

The zero return is a branch marker. It does not mean the child's actual PID is zero. The child obtains its identity with getpid().

The following fragment belongs inside a function. It deliberately uses _exit() in the child, a termination function explained below. The parent must still collect this child with waitpid().

c
int sample = 12;
pid_t child = fork();
if (child == -1) {
    perror("fork");
    /* Report failure to this function's caller. */
} else if (child == 0) {
    sample = 34;
    _exit(sample);
} else {
    /* sample is still 12 here; child identifies whom to wait for. */
}

The child starts with the parent's stack, heap and global variable contents. The stack holds function-call data; the heap holds dynamically allocated objects. Changing the child's sample leaves the parent's value unchanged.

Linux avoids eagerly copying all those bytes. A mapping connects program-visible addresses to memory or file storage. makes creation cheaper. Private describes visibility, not immediate physical separation.

1Create a distinct child

The kernel allocates a child identity and execution state. The child resumes at fork's return, not at main(). A thread is one execution path inside a process. Only the calling thread is replicated.

2Separate writes when necessary

A page is a unit of memory managed by hardware and the kernel. A page table maps program-visible addresses to physical memory. Initially, suitable private pages can point to shared physical pages with write protection.

A write can trigger a page fault: hardware asks the kernel to resolve a memory-access condition. The kernel copies the page when needed, updates mappings, and retries the instruction. It can also reuse a page if sharing has already ended. Explicit shared mappings remain shared; they are not made private by fork.

3Let each process proceed

There is no promise that the parent runs first. Multiple CPU cores can run both processes simultaneously. sleep() does not establish a reliable execution order. Waiting or another explicit synchronization mechanism establishes the relationship you need.

Step by stepFrom one launcher to a collected result
  1. Prepare: The parent builds arguments and decides which resources the child needs.

  2. Fork: The kernel creates the child with a distinct identity.

  3. Branch: The parent receives the child's PID; the child receives zero.

  4. Execute: The child replaces its program with the requested executable.

  5. Terminate: The child finishes and leaves a result for its parent.

  6. Collect: The parent waits for that child and consumes its result.

Memory support on small boards

ARM Linux applications use the same interfaces. Copy-on-write needs a memory management unit, hardware that translates and protects memory accesses. Some systems without one cannot provide ordinary fork. Even with it, task creation and page-table work cost time and memory. Measure this overhead before choosing how to launch frequent helpers.

Branch on the fork resultfork resultFailure: minus oneNo child createdParent: positive PIDTrack the new childChild: zeroSeparate execution pathfork resultFailure: minus oneNo child createdParent: positive PIDTrack the new childChild: zeroSeparate execution path
The fork return value selects failure, parent or child behavior
03

Replace the program and choose its inputs

4 min read

The is replaced by an exec operation. This is how your shell starts mycp without turning itself permanently into mycp: it forks first, then the child executes the tool.

execve() takes a path, an argument array and an environment array. Both arrays end with a null pointer. Each element before that points to a C string ending in a zero byte. These are two different kinds of termination.

This fragment requests a fixed executable with a small custom environment. If it succeeds, execution never reaches perror():

c
char *args[] = { "env", NULL };
char *settings[] = { "PATH=/usr/bin:/bin", "MODE=training", NULL };
execve("/usr/bin/env", args, settings);
perror("execve");
/* In a fork child, finish this failure path with _exit(...). */

argv[0] conventionally names the command. It is supplied by the caller, so it is not proof of executable identity. BusyBox uses command names to select applets, which makes that convention especially visible on embedded images.

1Choose a wrapper

The exec family offers different ways to supply the same basic inputs. The letter l means a list of arguments in the call; v means a vector, another name for an array. p requests PATH lookup. e supplies an explicit environment.

Function Arguments Program selection Environment
execl List Given path Caller's environment
execlp List PATH search Caller's environment
execle List Given path Explicit array
execv Array Given path Caller's environment
execvp Array PATH search Caller's environment
execve Array Given path Explicit array

For list forms, terminate the arguments with (char *)NULL. With execle, the environment array follows that terminator. A path may be relative; lacking p does not require an absolute path.

With execvp, a name containing / is used as a path rather than searched. Without /, directories from PATH are searched. An unrecognized executable format can trigger the documented shell fallback in execlp and execvp. A fixed execve() path avoids that implicit shell behavior. See exec(3).

2Understand environment ownership

The carries settings such as PATH, HOME and locale choices. extern char **environ; declares access to the caller's environment array. getenv("HOME") retrieves a value pointer or returns NULL if absent.

setenv(name, value, overwrite) copies the supplied strings and returns zero on success. With overwrite zero, it keeps an existing value. unsetenv(name) removes a name. Check both functions for -1; names cannot be empty or contain =. An absent variable and a variable with an empty value are different cases.

putenv() installs the supplied string itself. Changing it can change the environment. A local array that goes out of scope is unsafe. Allocated storage must remain alive until the entry is removed or replaced. Prefer setenv() for simpler ownership.

Fork gives the child a copy of this memory state. A child's setenv() never updates its parent's environment. Successful exec uses the array you selected; it does not consult the parent's live variables afterward. Avoid changing shared environment storage concurrently with launching from multiple threads.

3Handle replacement and failure

On success, the loader builds the new image and starts its entry code. For a dynamically linked ELF executable, the kernel also loads the interpreter named in its ELF metadata. That interpreter loads libraries before ordinary main() begins. Existing stdio buffers and registered exit handlers are discarded, not flushed or run.

On an ordinary failure, exec returns -1 and sets errno. ENOENT may mean a missing executable, script interpreter or ELF interpreter. ENOEXEC can indicate an unsupported format or wrong architecture. EACCES can indicate permissions or a filesystem mounted with execution disabled. E2BIG means the argument and environment data exceed execution limits.

The new image keeps descriptors unless their FD_CLOEXEC flag is set. O_CLOEXEC requests that flag when opening a file. This lets you keep standard input, output and error while closing private service files automatically. The preserved/reset distinction is documented in execve(2).

The inputs to execExecutable pathSelects the replacement programargvArgument pointers ending with NULLenvpEnvironment pointers ending with NULLSurviving descriptorsClose-on-exec entries are closedSame process identityNew program image; same PIDInputs shape the replacement imageExecutable pathSelects the replacementprogramargvArgument pointers ending withNULLenvpEnvironment pointers endingwith NULLSurviving descriptorsClose-on-exec entries areclosedSame process identityNew program image; same PIDInputs shape the replacementimage
A process keeps its identity while exec selects a new image and its inputs
04

Finish a child and read its result

3 min read

return 0; from the initial call to main() performs normal program termination, like exit(0). exit() runs functions registered with atexit() and flushes C stdio streams. Handlers run in reverse registration order. Returning from some other function only returns to its caller.

_exit() skips those user-space handlers and stdio flushing. The kernel still closes process descriptors and releases resources. Closing may itself take time, so skipping stdio does not promise instant termination. In glibc, the _exit() wrapper terminates all threads using the kernel's thread-group exit operation.

Use _exit() after a failed exec in a fork child. The parent's cleanup registrations and buffered output belong to the parent's program. Running them again in the child can duplicate output or remove a shared temporary file prematurely.

For the wait interfaces here, ordinary exit status contains the low eight bits of the supplied value. Zero conventionally means success. Use values from 0 through 255 deliberately; returning 256 does not communicate a distinct failure through WEXITSTATUS().

is usually done with wait() or waitpid(). A successful call returns a child's PID. Its status pointer receives encoded information, not just the child's exit value.

Test Extract only after that test succeeds Meaning
WIFEXITED(status) WEXITSTATUS(status) Normal termination, including nonzero exit
WIFSIGNALED(status) WTERMSIG(status) A signal ended the child
WIFSTOPPED(status) WSTOPSIG(status) Child execution was stopped
WIFCONTINUED(status) No numeric extraction needed A stopped child resumed

A signal is a kernel-delivered notification that may terminate, stop or otherwise affect a process. The next lesson teaches handlers. For now, distinguish a signal number from an exit code. Shell conventions such as 128 + signal are a shell's representation, not the raw wait status.

wait(&status) means any child, blocking until a termination result exists. It is equivalent to waitpid(-1, &status, 0). A positive first argument selects that exact child. Zero selects children in the caller's process group; values below -1 select the group whose ID is the argument's absolute value. A process group is a collection used for coordinated signal delivery.

The wait loop must retry EINTR, which means a caught signal interrupted the wait. Other errors need handling. ECHILD means no matching waitable child exists; it is not evidence of successful completion. For an ordinary untraced child, options zero waits for termination. Add WUNTRACED for stopped reports and WCONTINUED for resumed reports. Those reports do not reap a still-living child.

WNOHANG makes the call return zero when matching children exist but no requested change is available. Do not decode an untouched status after that return. Do not spin on it continuously: busy polling wastes a board's CPU and power. Details and option rules appear in wait(2).

Decode the reported eventNormal exitSignalterminationStopped childTest firstWIFEXITEDWIFSIGNALEDWIFSTOPPEDExtract detailWEXITSTATUSWTERMSIGWSTOPSIGChild finishedYesYesNoOrdinary waitReportedReportedNeedsWUNTRACED
Wait status decoding depends on which child state change occurred
05

Build mysh v1 around one child

4 min read

Start with intentionally small command syntax: words separated by spaces or tabs. There is no quote processing, wildcard expansion, pipeline, redirection or background execution. Characters such as * and | become ordinary argument text. Do not use this parser for general shell scripts.

1Keep shell changes in the parent

cd must call chdir() in the shell itself. Changing a child's working directory leaves the parent's directory unchanged. exit also belongs in the parent. This version accepts cd directory, uses HOME for bare cd, and accepts bare exit to return the last result.

2Implement the launch loop

Save this complete program as mysh.c. _POSIX_C_SOURCE enables the POSIX declarations used by getline() and strtok_r() under strict C compilation. getline() returns a signed byte count, so its result type is ssize_t.

c
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

enum { MAX_ARGS = 64 };

int main(void)
{
    char *line = NULL;
    size_t capacity = 0;
    int last = 0;
    int interactive = isatty(STDIN_FILENO);

    for (;;) {
        if (interactive) {
            if (fputs("mysh> ", stdout) == EOF || fflush(stdout) == EOF) {
                last = 1;
                break;
            }
        }

        errno = 0;
        ssize_t length = getline(&line, &capacity, stdin);
        if (length == -1) {
            if (errno == EINTR) {
                clearerr(stdin);
                continue;
            }
            if (!feof(stdin)) {
                perror("getline");
                last = 1;
            }
            break;
        }
        if (memchr(line, '\0', (size_t)length) != NULL) {
            fputs("embedded zero byte rejected\n", stderr);
            last = 2;
            continue;
        }

        char *args[MAX_ARGS + 1];
        size_t count = 0;
        char *save = NULL;
        char *word = strtok_r(line, " \t\r\n", &save);
        while (word != NULL && count < MAX_ARGS) {
            args[count++] = word;
            word = strtok_r(NULL, " \t\r\n", &save);
        }
        if (word != NULL) {
            fputs("too many arguments\n", stderr);
            last = 2;
            continue;
        }
        args[count] = NULL;
        if (count == 0)
            continue;

        if (strcmp(args[0], "exit") == 0) {
            if (count != 1) {
                fputs("usage: exit\n", stderr);
                last = 2;
                continue;
            }
            break;
        }
        if (strcmp(args[0], "cd") == 0) {
            if (count > 2) {
                fputs("usage: cd [directory]\n", stderr);
                last = 2;
                continue;
            }
            const char *directory = count == 2 ? args[1] : getenv("HOME");
            if (directory == NULL) {
                fputs("cd: HOME is absent\n", stderr);
                last = 1;
            } else if (chdir(directory) == -1) {
                perror("cd");
                last = 1;
            } else {
                last = 0;
            }
            continue;
        }

        if (fflush(NULL) == EOF) {
            perror("fflush");
            last = 1;
            continue;
        }
        pid_t child = fork();
        if (child == -1) {
            perror("fork");
            last = 1;
            continue;
        }
        if (child == 0) {
            execvp(args[0], args);
            int saved_error = errno;
            perror(args[0]);
            _exit(saved_error == ENOENT ? 127 : 126);
        }

        int status;
        pid_t collected;
        do {
            collected = waitpid(child, &status, 0);
        } while (collected == -1 && errno == EINTR);
        if (collected == -1) {
            perror("waitpid");
            last = 1;
            break;
        }
        if (WIFEXITED(status)) {
            last = WEXITSTATUS(status);
            printf("child %jd exited: %d\n", (intmax_t)child, last);
        } else if (WIFSIGNALED(status)) {
            int signal_number = WTERMSIG(status);
            last = 128 + signal_number;
            printf("child %jd terminated by signal: %d\n",
                   (intmax_t)child, signal_number);
        }
    }
    free(line);
    return last;
}

args points into line, which remains valid through the child's exec attempt. The parent waits before reusing it. Saving errno before perror() preserves the error used to choose failure status.

The values 126 and 127 are useful shell conventions for launch failures. They do not prove that exec failed: a successfully launched program can return either value itself. The shell prints the actual terminating signal separately, keeping that evidence visible.

3Compile and exercise observable behavior

Compile on Linux, then feed simple commands through a pipe. The outer shell's printf supplies input; it is not syntax implemented by mysh.

bash
cc -std=c11 -Wall -Wextra -Wpedantic -O0 -g mysh.c -o mysh
printf '/bin/true\n/bin/false\nmissing-training-command\nexit\n' | ./mysh
./mysh

Check that each external command produces a status line and the prompt returns. Check that cd /tmp changes a subsequent pwd. Empty lines should launch nothing. The shell's own final status follows its last command or built-in result.

Limits of this first shell

This version is single-threaded; its child-side perror() relies on that scope. Ctrl-C can affect the shell, and a stopped child can leave it waiting. Signals and job control come next. Use interactive mode for commands that read stdin: a script reader's getline() can read ahead, leaving the child without expected input.

getline() grows its allocation to fit input. The argument count is bounded, but line memory is not. A product accepting untrusted input needs a bounded reader that consumes and rejects oversized lines. On a small board, check that external applet paths actually exist instead of assuming a desktop filesystem layout.

The foreground shell loopRead lineSplit wordsBuilt-in?Handle inparentFork childExit from step 3: Built-in completeNext line or exitParentwaitpidChild independentlyattemptsexecvpPrintresult↻ Repeat from step 1Read lineSplit wordsBuilt-in?Handle inparentFork childExit from step 3: Built-incompleteNext line or exitParentwaitpidChild independentlyattemptsexecvpPrintresult↻ Repeat from step 1
The parent handles built-ins and collects the single external child before reading again
06

What stays separate and what stays shared

5 min read

Suppose you open a regular file before fork. The child reads three bytes and exits. After the parent collects it, a normal read() through the inherited descriptor starts at the advanced position. The child changed a shared kernel file offset, not a variable in the parent's heap.

An is the shared object here. The parent's and child's descriptor tables are distinct. Both tables can refer to the same description.

Closing a descriptor in the child removes its reference. It does not close the parent's descriptor. Changing a descriptor flag such as FD_CLOEXEC also affects only that descriptor entry. In contrast, changing a shared status flag such as O_NONBLOCK affects users of the same open file description. Opening the path again creates another description with an independent offset.

1Separate C buffers from kernel state

printf() may retain bytes inside the C library until flushing. Fork duplicates that buffer in private memory. If both processes later call exit(), each can write its copy, producing duplicated output. Redirection to a file often exposes this because newline output need not flush a fully buffered stream.

Flush pending output before fork when that output belongs to the parent. Then use _exit() on a child exec failure. Successful exec discards copied buffers. This bug combines deterministic buffer duplication with timing-dependent ordering; waiting afterward does not undo the duplication.

Buffered input needs care too. A parent can read ahead from a file into its private stdio buffer. The shared kernel offset then lies beyond the bytes the parent has consumed logically. A child reading the inherited descriptor sees that advanced offset, not the parent's buffered bytes. Avoid mixing independent buffered readers around fork without explicit coordination.

2Track preserved and reset attributes

A signal's disposition is its configured action: default, ignore or a handler function. A signal mask lists signals temporarily blocked from delivery. Pending signals have been generated but not yet delivered. These terms become practical in the next lesson.

Attribute After ordinary fork After successful exec
PID New child PID Preserved
Private address space Logically copied Replaced
Working directory and creation mask Copied Preserved
Caught signal dispositions Copied Reset to default
Ignored signal dispositions Copied Preserved on Linux
Signal mask Copied from calling thread Preserved
Pending signals Child starts empty Preserved
Descriptors Copied references Kept unless close-on-exec
atexit registrations Copied Discarded

The creation mask, set by umask(), removes permissions from newly created files. Real user and group IDs survive exec. Effective credentials can change for specially marked executable files, subject to Linux security restrictions.

Traditional process-associated fcntl record locks are not inherited by the child. The parent's locks normally survive its own exec, although closing a descriptor for that file can release them. Linux open-file-description locks and flock() locks follow the inherited open description instead. Say which lock family you mean.

Going deeperFollow the objects through kernel source

The kernel represents a task with task_struct. Its memory description uses mm_struct; descriptors are reached through files_struct. In your board's matching Linux source tree, start in kernel/fork.c for creation, fs/exec.c for replacement, and kernel/exit.c for exit and waiting. Memory write-fault handling lives under mm/, notably mm/memory.c. These internal structures and helpers can evolve.

Do not equate a process's virtual size with newly copied physical memory after fork. Page-table work, task allocation and later write faults contribute different costs. On a memory-limited board, latency can increase when either side dirties many private pages, even if creation itself seemed cheap.

Going deeperForking a threaded process

Threads share process memory and resources. Fork copies only the calling thread, but memory can contain locks owned by vanished threads. A mutex permits one lock owner at a time. Child-side allocation or stdio may deadlock on inherited library state.

After fork in a multithreaded process, restrict the child to async-signal-safe operations until exec. Async-signal-safe means the function can run safely when it interrupts another operation in the same process. write(), close(), execve() and _exit() are key building blocks. Ordinary formatting and memory allocation do not qualify.

pthread_atfork(prepare, parent, child) registers callbacks around fork. Prepare callbacks run in reverse registration order; parent and child callbacks run in registration order. They help coordinate known state, but cannot repair arbitrary third-party locks or remove the child-side safety restriction. Prefer controlled spawn actions when they express the setup you need.

Two tables reference one openOpen file descriptionShared offset and status flagsParent descriptorOwn entry and descriptor flagsChild descriptorOwn entry and descriptor flagsOpen file descriptionShared offset and statusflagsParent descriptorOwn entry and descriptorflagsChild descriptorOwn entry and descriptorflags
Descriptor entries are copied while their open file description remains shared
07

Zombies, orphans and deliberate observation

3 min read

A no longer runs application code. Its address space and ordinary open descriptors have been released. The kernel retains identity, termination status and accounting information needed for waiting.

A short zombie interval is normal: the child can finish before waitpid(). A growing population means the launcher fails to collect every result. Zombies consume kernel resources and retain PID identities.

For the lab, make one child exit while its parent pauses before waiting. Print both PIDs and keep the experiment bounded. In another terminal, set child to the printed child PID, then inspect it:

bash
ps -o pid,ppid,stat,comm -p "$child"
cat "/proc/$child/status"

Look for Z in the state field while the parent remains alive. After the parent waits, the corresponding entry should disappear. Do not replace waiting with a delay and assume collection happened. Sending a terminating signal to a zombie cannot make already-finished application code terminate again.

An may still be running. Linux reparents it to an eligible ancestor , or otherwise to the namespace's init process. A service supervisor can opt into this role with prctl(PR_SET_CHILD_SUBREAPER, 1).

Reparenting does not kill a running child or always change its parent PID to 1. Adopting supervisors must wait for terminated adoptees; container entrypoints can accumulate zombies too.

1Decide who owns each child

Assign one component responsibility for collecting each child's result. In a shell with several children, a broad waitpid(-1, ...) can consume a result another component expected. Keep a PID-to-job record when the launcher grows beyond mysh v1.

2Use structured observation when needed

waitid() reports into siginfo_t, a structure describing a child event. Select a specific child with P_PID, use WEXITED for termination, and check the return value. si_code distinguishes events such as CLD_EXITED and CLD_KILLED; si_status then means an exit value or a signal number. Do not pass it to WEXITSTATUS().

WNOWAIT observes a waitable event without consuming it. A terminated child remains available for a later collecting wait. This is useful for inspection, but forgetting that second wait creates a leak. With WNOHANG, initialize the structure to zero and inspect si_pid after a successful call to distinguish no event portably.

In this experiment, exit(0) leaves a zombie; waitid with WEXITED | WNOWAIT observes its result and leaves it waitable, while a collecting waitpid releases the record. Stopping and continuing a living child do not reap it.

  • states: [{"id": "running", "label": "Running child"}, {"id": "stopped", "label": "Stopped child"}, {"id": "zombie", "label": "Zombie: termination record retained"}, {"id": "reaped", "label": "Reaped: record released"}]
  • transitions: [{"from": "running", "to": "stopped", "event": "Stop child"}, {"from": "stopped", "to": "running", "event": "Continue child"}, {"from": "running", "to": "zombie", "event": "exit(0)"}, {"from": "running", "to": "zombie", "event": "Terminating signal"}, {"from": "stopped", "to": "zombie", "event": "Terminating signal"}, {"from": "zombie", "to": "zombie", "event": "waitid: WEXITED | WNOWAIT"}, {"from": "zombie", "to": "reaped", "event": "Collect with waitpid"}]

Explicitly setting SIGCHLD to SIG_IGN, or using SA_NOCLDWAIT, can prevent zombies on Linux, but also prevents ordinary status collection. The default disposition's ignored action is not equivalent to explicitly installing SIG_IGN. A shell that prints results needs a real collection strategy.

A result waits for collectionLive childStopped childZombieRecord releasedTransitionsStop signalLive childStopped childSIGCONTStopped childLive childExitLive childZombieCollecting waitZombieRecord releasedLive childStopped childZombieRecord releasedTransitionsStop signalLive childStoppedchildSIGCONTStoppedchildLive childExitLive childZombieCollecting waitZombieRecordreleased
Exit leaves a waitable zombie; collection releases the remaining process record
08

Choose a safer launch mechanism

4 min read

vfork() is not a drop-in faster fork. On Linux, its child shares the parent's memory, including the stack, while the calling parent thread is suspended. Other parent threads can still run. A child that modifies ordinary data, returns from the calling function or runs normal cleanup can corrupt the parent.

Keep any direct vfork child path limited to a tightly controlled exec attempt and _exit() on failure. Even debugging prints violate the assumptions you were trying to preserve. Prefer a library launch interface rather than hand-writing this fragile path; see vfork(2).

posix_spawn() creates a process that runs a selected path. posix_spawnp() adds PATH lookup. You prepare file actions and attributes in the parent: close a descriptor, duplicate one for output, open a file, or choose a signal mask. The library performs those operations without asking your application to run arbitrary child-side C code.

Modern glibc can implement spawning with shared-memory clone semantics and a controlled child stack. This avoids much fork overhead and many post-fork library-lock hazards. Calling spawn does not make the entire application race-free: unrelated threads can still alter environment storage or open inheritable descriptors.

Spawn functions return an error number directly, rather than using the usual -1 plus errno rule. Check that return before using the output PID. On reported success, still collect the child. Portable code must account for certain setup or execution failures appearing as child status 127. See posix_spawn(3).

Linux clone() exposes finer resource-sharing controls. CLONE_VM shares an address space. CLONE_FS shares working-directory, root-directory and creation-mask state. CLONE_FILES shares the descriptor table itself, so one task's close removes that table entry for the other. This differs from ordinary fork's separate tables referencing shared open descriptions.

These flags are independent dimensions subject to kernel validity rules. They do not each mean create a POSIX thread. Use the thread library for threads; raw clone requires careful stack, lifetime and library integration work. glibc's fork wrapper may appear as clone in a trace rather than a literal fork syscall. Consult clone(2) when decoding flags.

1Decide whether a shell is required

system() interprets a command string using a shell. popen() also runs a shell command and gives you a C stream connected to its input or output through a pipe. A pipe transfers bytes between processes. Close a popen stream with pclose(), which also collects the command's result; fclose() is insufficient.

Shell interpretation makes constructed command strings dangerous. A filename containing shell metacharacters can become another command. Passing arguments separately through execve() avoids shell parsing, but the target program still interprets its own options. Use -- before untrusted operands when that program supports it. Use fixed executable paths and a deliberately chosen environment for privileged launchers.

2Understand the full system behavior

Implementing system() correctly requires more than fork, exec and one wait. The caller temporarily ignores SIGINT and SIGQUIT and blocks SIGCHLD; the child needs appropriate original signal behavior. These changes protect the caller while allowing the command to respond normally. The library's result is an encoded wait status. See system(3).

Step by stepRequirements for a single-threaded system-like implementation
  1. Save: Record the original signal actions and mask; handle a null command as a shell-availability query.

  2. Protect: Ignore interrupt and quit signals in the caller and block child-status notification.

  3. Create: Fork while recording failures and preserving the error needed by the caller.

  4. Restore child: Restore the original mask; make caught interrupt and quit actions default, preserving originally ignored actions.

  5. Run shell: Execute /bin/sh with sh, -c and the command string; use _exit(127) if execution fails.

  6. Collect: Wait for exactly the shell child, retry EINTR, then restore caller state on every parent path.

Going deeperThe details that keep system-like code honest

Restoring all resources on partial failure is part of the implementation. Save the relevant errno before restoration calls can overwrite it. Return -1 when creation or status collection fails; otherwise return the encoded status. Do not confuse failure to execute the shell with a command deliberately returning 127.

Signal dispositions are shared among threads, while masks belong to individual threads. A threaded implementation needs coordination for overlapping calls and cancellation cleanup. Merely blocking SIGCHLD in one thread does not prevent another thread from consuming the child. Use libc's implementation in products unless you have a concrete reason and tests for replacing these semantics.

Choose how to launchfork and execposix_spawnsystemChild setupApplicationcodePreparedactionsShell managescommandShell parsingAvoid withexecveNot implicitYesResultcollectionApplicationwaitsApplicationwaitsLibrary waitsKey concernChild-sidesafetyResourceinheritanceCommandinjection
Launch interfaces trade flexible child code for controlled setup and shell interpretation
09

Common mistakes and a disciplined trace

3 min read

Creation fails with EAGAIN. A process-count or task limit may be exhausted. RLIMIT_NPROC applies to the real user ID and counts Linux threads, with documented privilege exceptions. A cgroup is a kernel-managed resource group. Its PID controller can reject creation at pids.max, independently of the shell limit. System-wide task and PID limits can also matter.

Inspect limits before changing them. These commands read the calling shell's settings and its cgroup membership:

bash
ulimit -u
cat /proc/$$/limits
cat /proc/$$/cgroup
cat /proc/sys/kernel/threads-max
cat /proc/sys/kernel/pid_max

ulimit -u is available in bash, but is not a portable POSIX-shell option. On cgroup v2, use the membership path to locate pids.current, pids.max and pids.events under the mounted hierarchy. Also inspect limiting ancestors. Do not assume every container shows the host's mount or hierarchy. The PID controller documentation explains hierarchical enforcement.

Fix uncontrolled launching, missing reaping or an undersized service limit as appropriate. Do not loop immediately on failed fork. A fork bomb is uncontrolled recursive creation that exhausts task resources. Diagnose limits using a bounded test in isolation, never a fork bomb. ENOMEM indicates a different creation problem, such as insufficient memory for kernel structures.

The executable exists but will not start. Check the saved exec error, then inspect the file with file and readelf -l. Verify its architecture and interpreter path on the target. A cross-compiled program can exist while its requested loader is absent. Ship the matching runtime or choose a deliberate static build with the required archives.

A helper unexpectedly holds a service resource. Inherited descriptors can keep files, pipes or sockets alive. Inspect /proc/<pid>/fd and trace opens and closes. Set close-on-exec atomically during creation with O_CLOEXEC or an API-specific equivalent. In threaded code, open-then-fcntl(F_SETFD) leaves a window where another thread can launch before the flag is set.

Logs repeat after a failed command. Trace write() calls and inspect pre-fork stdio buffering. Flush intended parent output before fork, and finish the child failure path with _exit(). Do not attempt to solve duplicated buffers by adding a sleep.

Children accumulate or results belong to the wrong job. Look for Z with ps, audit every successful creation path, and check which component calls wait. Wait for the specific PID when that component owns only one command. Later, one central reaper can distribute results to job records.

Use strace to observe the whole launch cycle, including child system calls. Save traces in your lab directory:

bash
strace -f -e trace=process ./mysh
strace -f -e trace=process,openat,close,fcntl,dup2,write ./mysh

Read the events: creation returns an identity, exec selects a program, exit records completion, and wait consumes it. glibc may use clone for fork and wait4 for waitpid. Build strace for your board or include it in a diagnostic image. Tracing changes timing; it does not establish production latency.

For the inheritance lab, deliberately open one harmless descriptor without close-on-exec and one with it. Launch an inspector and compare surviving descriptor identities. Do not infer leakage just from a reused descriptor number: the new program may open its own resource using the same integer. Compare targets and the open/close trace.

Match evidence to the stageCreationfork errnoTask limitsPID controllerExecutionexec errnoArchitectureLoader pathInheritanceprocfs fd linksOpen/close traceCLOEXEC flagsCollectionZ stateWait ownershipDecoded statusFind the first failing stage
Creation, execution, inheritance and collection failures require different evidence
10

Try it

1 min read

Open the lab to implement mysh v1 and verify command results, failed launches, blank lines and parent-side built-ins. Then create one bounded zombie experiment, observe its state, and show that collecting its result removes the record. Trace fork and exec with strace -f, including the descriptor-inheritance comparison. Use the practice pack for deeper work on custom environments, waitid observation and process limits before moving to Signals (mysh v2).

Practice the process lifecycleBuild myshLaunchcommandsand inspectresultsObserve azombieInspectbefore andaftercollectingTraceinheritanceComparedescriptortargetsacross execBuild myshLaunchcommandsand inspectresultsObserve azombieInspectbefore andaftercollectingTraceinheritanceComparedescriptortargetsacross exec
Practice moves from launching commands to collecting results and inspecting inheritance

Key takeaways

  • fork creates a child; exec replaces its program; wait collects a child's result.
  • Private memory changes separate after fork, but inherited descriptors share open file descriptions.
  • Successful exec keeps the PID and preserves descriptors unless close-on-exec is set.
  • Arguments and environments are null-terminated arrays of pointers to terminated strings.
  • Interpret wait status only with the matching WIF and W macros.
  • Use _exit after a failed child exec to avoid running inherited cleanup.
  • A zombie has finished; an orphan has lost its original parent.
  • posix_spawn limits child setup, but applications still own descriptor and environment races.

Reflect

  1. Explain to a colleague, in two sentences: identify a process and its parent using getpid, getppid and procfs.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?

On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

Practise this lessonExercises, quiz, interview preparation and spaced review

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close