Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 66 ยท Processes

Process Creation and Termination

Learn how processes are created with fork and exec, how the process tree forms, how wait and exit work, and what zombie and orphan processes are, with a fork simulator.

Processes do not appear from nowhere. Every process except the very first one is created by another process, its parent. The new process is the child, and the family tree that results explains many things you see in a task manager. In this lesson you will learn how a parent creates a child, how the child ends, and what happens in awkward cases such as a child that finishes before anyone collects its result (a zombie) or a parent that dies first (an orphan).

The classic UNIX design splits creation into two small calls, fork and exec, while Windows uses a single CreateProcess. Understanding why UNIX chose two calls is a great way to understand the OS's philosophy.

UNIX creates processes in two steps

fork() Clone the calling process.
exec() Replace the clone's program.
wait() Parent collects the child's exit status.
exit() Child ends and frees resources.

Windows does fork plus exec in one call, CreateProcess.

1 / 2

The process tree

The kernel starts one process (init or systemd, PID 1). That process creates others, which create others, forming a tree. Every process records its parent's PID. Tools such as pstree (Linux) or Process Explorer (Windows) show the tree. When you type a command in a shell, the shell forks a child and the child execs the command.

When a process creates a child, the OS must decide:

  • Resources: does the child get its own, or share the parent's? UNIX children get copies; some systems let the parent limit the child's resources.
  • Execution: do parent and child run concurrently, or does the parent wait until the child finishes (a shell waits for a foreground command, but not for one started with &)?
  • Address space: is the child a duplicate of the parent, or does it load a new program?

fork(): cloning a process

fork() creates a new process that is a near-exact copy of the caller: same code, same variables, same open files, same program counter. It is called once but returns twice: in the parent it returns the child's PID; in the child it returns 0; on failure it returns -1. That return value is how each copy knows which one it is.

Modern kernels use copy-on-write: the child initially shares the parent's memory pages, and a private copy of a page is made only when one of them writes to it. This makes fork fast even for big processes.

C
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork failed");
        return 1;
    } else if (pid == 0) {
        printf("child: my PID is %d\n", getpid());
        execlp("ls", "ls", "-l", NULL);   // replace this process's program
    } else {
        int status;
        waitpid(pid, &status, 0);          // parent waits for the child
        printf("parent: child %d finished\n", pid);
    }
    return 0;
}

exec(): loading a new program

The exec family (execve, execlp, ...) replaces the current process's code, data, heap and stack with a new program loaded from a file. The PID stays the same and open files usually stay open, but the old program is gone: exec does not return unless it fails. The combination fork then exec is how a shell runs ls: clone itself, then turn the clone into ls.

Why two steps? Between fork and exec the child can adjust things (redirect its output to a file, change directories, drop privileges) before the new program starts. That is how shell redirection and pipes are built.

Simulating fork

Pyodide cannot create real processes, so this stand-in models a process table with fork, exec, exit and wait and prints the same kinds of results you would get from the real calls.

Python A fork, exec and wait simulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Termination

A process ends in one of these ways:

  • Normal exit: it finishes main or calls exit(status).
  • Error exit: it detects a problem and exits with a non-zero status.
  • Fatal error: an illegal instruction, divide by zero or invalid memory access; the OS kills it.
  • Killed by another process: a signal such as SIGTERM (polite request) or SIGKILL (cannot be caught).

On termination the OS frees the process's memory, closes its files, and keeps only a small entry holding the exit status until the parent has read it with wait().

Zombie processes

A process that has terminated but whose parent has not yet called wait() is a zombie (state Z). It uses no memory or CPU, only a process-table slot. If a buggy parent never waits, zombies pile up and can exhaust the table. They disappear when the parent waits or itself exits.

Orphan processes

If the parent exits first, the child is an orphan. The kernel gives it to init (PID 1) as its new parent, and init calls wait() regularly, so the orphan is cleaned up when it finishes.

Cascading termination

Some systems (and options such as process groups or Windows job objects) terminate all children when the parent ends. UNIX does not do this by default: shells send SIGHUP to their jobs when a terminal closes.

Exit status in practice

By convention 0 means success and anything else means failure. A shell exposes it as $?. The next example shows a parent making a decision based on child exit codes, using functions as stand-in children.

Python Using exit codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Windows and other differences

Windows has no fork. CreateProcess creates a new process and loads a program in one step, and the parent gets a handle to it. On Linux, posix_spawn and vfork exist as faster alternatives for the fork-then-exec pattern. Containers and threads (clone() on Linux) are variants where parent and child share varying amounts of state.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fork() return in the child process?

    fork returns 0 in the child and the child's PID in the parent; -1 means failure.
  2. 2. What does exec() do?

    exec loads a new program into the same process, so it never returns on success.
  3. 3. What is a zombie process?

    Zombies have finished but still occupy a process-table entry until the parent calls wait().
  4. 4. Who adopts an orphan process on UNIX?

    init becomes the new parent and reaps the orphan when it finishes.
  5. 5. Why does copy-on-write make fork cheap?

    Because physical pages are shared until modified, forking a large process does not copy all of its memory.

Summary

  • Processes form a tree; every process has a parent, and PID 1 is the root.
  • UNIX creates processes with fork (clone) and exec (replace the program); Windows uses CreateProcess.
  • wait lets the parent collect the child's exit status; until then a finished child is a zombie.
  • Orphans are adopted by init. Termination releases the process's resources.
  • Copy-on-write makes fork efficient.

Next: Inter-Process Communication