Study guides · Intermediate

Follow Linux process creation, replacement, exit and reaping

Separate fork, exec, exit and wait boundaries, then run successful and failed image replacement and inspect child status.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Separate creation, image replacement and exit
  2. Exec replaces an image rather than adding a PID
  3. Distinguish terminated from reaped
  4. Execute both success and failure paths
  5. Parent lifetime does not define child lifetime automatically
  6. Add assumptions for a multithreaded parent
  7. Track descriptor numbers and referenced objects separately
  8. Map child status to an application result explicitly
  9. Exercise: identify the waited PID and status interpretation
  10. Ask Logeia about this articleCheck your understanding

Separate creation, image replacement and exit

Start with a server launching an external command and waiting for its result. Fork creates a process, exec replaces a process image, exit ends execution, and wait collects a child's termination status. These are different boundaries. Combining them into the phrase start a child hides failure handling and cleanup ownership. We follow one Linux parent and child before considering a larger service.

A successful fork returns the child PID in the parent and zero in the child. Both continue after the call, but their relative execution order is unspecified. Printed line order is not synchronization evidence. Use waitpid or an explicit communication channel where ordering is required. Distinguish copied address-space values from kernel resources referenced by both processes; that distinction determines what can remain shared after creation.

Exec replaces an image rather than adding a PID

The child uses execl to run a shell command that exits with status seven. Successful exec does not return to the next line of the original child program. The process identity continues while its program image changes, so the parent still waits for the PID returned by fork. Exec is not an additional grandchild-creation step.

Arguments, environment and inherited descriptors also need a contract. An unnecessary pipe or socket reference retained across exec can keep a resource alive after the parent expects it to close. Use explicit inheritance and close-on-exec rules in a full launcher. The small example focuses on creation, image replacement and reaping, rather than presenting complete descriptor inheritance, credential management or process-supervision code for an arbitrary production command.

StageChildParent
Successful forkContinue as a separate processReceive child PID
Successful execReplace program in same processCan wait independently
ExitExecution ends; status retainedReap with wait
Wait completesReapedInspect termination status

Distinguish terminated from reaped

A child can stop executing before its parent collects termination status. The kernel retains enough information for the parent to inspect that outcome later. Waitpid returning the requested PID allows the parent to interpret and reap it. Do not count an exited-but-unreaped child as still consuming CPU execution, but do not treat its lack of execution as permission to ignore cleanup indefinitely.

First distinguish normal exit from signal termination. Only after WIFEXITED succeeds should WEXITSTATUS be interpreted as the program's exit value. Comparing the raw status integer directly with seven is incorrect. A long-lived supervisor additionally handles interrupted waits and multiple children. This short assertion-based example intentionally does not claim every signal, restart or supervision policy of a production process launcher.

Execute both success and failure paths

Save the C source and compile with gcc, C11, optimization and warning flags. The first child successfully replaces its image and exits seven. The second attempts a deliberately nonexistent path and calls _exit(127) when exec returns. The parent reaps both PIDs and asserts normal exit with the chosen values. Status127 is this example's failure convention; it is not a child exit automatically supplied by exec itself.

Using _exit on the child failure path avoids unintentionally repeating inherited buffered I/O or exit handlers from before fork. A full launcher needs a deliberately chosen cleanup path rather than blindly running every parent shutdown routine. Record compiler, OS, exit code and output. PID numbers are intentionally not fixed expected values. The example passes no credentials and changes no external service.

c
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void){
    pid_t child=fork();assert(child>=0);
    if(child==0){execl("/bin/sh","sh","-c","exit 7",(char*)NULL);_exit(127);}
    int status;assert(waitpid(child,&status,0)==child);
    assert(WIFEXITED(status)&&WEXITSTATUS(status)==7);
    puts("child exec succeeded; exit=7; child reaped");
    child=fork();assert(child>=0);
    if(child==0){execl("/definitely-not-present-lavacs","x",(char*)NULL);_exit(127);}
    assert(waitpid(child,&status,0)==child);
    assert(WIFEXITED(status)&&WEXITSTATUS(status)==127);
    puts("exec failed; exit=127; second child reaped");
}

Parent lifetime does not define child lifetime automatically

Ending a parent does not universally terminate all children at the same instant. Adoption, reaping, process groups and service-manager policy affect what happens. Likewise abandoning a web request does not prove an external command stopped. A cancellation design specifies the signal target, wait deadline and collection of remaining resources, connecting process supervision to the earlier distinction between deadlines and completed side effects.

A shell launcher may add descendants whose working PID differs from the immediate child being waited on. This example's shell only exits, so its checks do not certify cleanup of an arbitrary process tree. Draw parent, child, group and service as distinct control units. When the cancellation target and actual work unit differ, apparently successful local cleanup can leave descendants or inherited resource references behind.

Add assumptions for a multithreaded parent

Forking from a single-threaded program differs from forking in a multithreaded server. The child continues from the calling thread, while library locks formerly held by other threads can create restrictions before exec. Follow the applicable POSIX and runtime rules for operations in that child interval. Adding casual buffered diagnostic calls may change the conditions being reasoned about.

An existing launcher library or posix_spawn may better fit a real application. The lesson explains creation versus replacement; it does not recommend fork for every server. Shell-string interpretation, arguments, credentials, working directory and environment inheritance are additional boundaries. This fixed-command example must not be presented as a ready-made safe facility for arbitrary user-supplied commands. Understand the process lifecycle before selecting the appropriate production interface.

Track descriptor numbers and referenced objects separately

Descriptors inherited across fork can exist in both parent and child without representing two independently reopened files. Shared kernel-side open-file state can affect properties such as offset. Keep the copied address-space variable story separate from the resource-reference story. The integer value of a descriptor alone does not describe ownership or independence.

For a pipe, closing the parent's write end may not produce the expected EOF while a child retains another write reference. Before blaming CPU speed or wait behavior for a stalled reader, list which process owns each end and when it closes. The supplied example does not add a pipe; this is a concrete design check for extending a launcher. For each resource, state whether it is inherited, closed on exec or explicitly closed by each participant. Those rules connect process lifetime to observable I/O completion and make cleanup failures easier to reproduce.

Map child status to an application result explicitly

A normal process exit with value seven is not automatically an application success. Seven is deliberately chosen for this exercise. A real command adapter must separately interpret process termination, the command's exit-code contract and validity of its output. Nonempty standard output alone is not a success criterion.

Cancellation likewise has several observable stages: signal sent, child terminated and status reaped. Failed exec differs from successful image replacement followed by failure of the new program. A dedicated status channel can report stages when that distinction matters. Define which event allows an acknowledgment to the caller, and retain enough information to diagnose an incomplete attempt. Starting, running, accomplishing the requested work and collecting lifetime are separate claims. This interpretation layer is essential when the process example becomes part of a web request rather than a standalone console test.

Exercise: identify the waited PID and status interpretation

After a child successfully execs and exits seven, the parent waits for the PID returned by fork. The old child code immediately after successful exec does not run. The parent checks WIFEXITED before reading seven through WEXITSTATUS. Image replacement does not require inventing a new PID for the same child.

Now consider failed exec falling through into code intended for the parent. That can duplicate parent work, so the child needs an explicit failure exit path and the parent still reaps it. A fuller error-reporting protocol might use a pipe, but that is separate from this example's127 convention. Map creation, replacement, termination and collection to both a diagram and the observed output. Those boundaries explain more than the vague claim that a command was started successfully.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Understand the systems behind the web · STEP 5

Choose a learning path