Skip to content

System Calls (fork · wait · exec) ​

A system call is the official window through which an application asks the operating system (kernel), "Please do this for me." Among them, fork(), exec() and wait() are the classic system calls for creating and controlling processes.

At a Glance ​

  • For security and stability, applications cannot touch the disk, memory or other processes directly. Work such as reading a file or creating a new process must always go through the operating system.
  • Analogy: it is like a bank counter. A customer (application) cannot walk into the vault (hardware), but if they hand an application form (system call) to the teller (kernel), the teller takes care of it for them.
  • When a system call is made, the CPU switches from the restricted user mode to the fully privileged kernel mode, runs the operating system code, and then switches back to user mode when it is done. This switch happens through the software interrupt mechanism described in the Interrupts article.

A structure where applications reach the CPU, memory and devices only through the kernel

Image source: Wikimedia Commons (Bobbo, CC BY-SA 3.0)

In the picture, the arrow between Applications and the Kernel is exactly the system call. Applications cannot reach the CPU, memory or Devices directly and must always go through the kernel.

text
 Application (user mode)
      │  calls fork(), read(), write() ...
      ▼
 ─────────────── Boundary (system call) ───────────────
      ▼
 Kernel (kernel mode): does the actual work and returns the result

This article covers three calls related to processes.

System callWhat it does
fork()Duplicates the current process to create a new process (the child)
exec()Replaces the contents of the current process entirely with another program
wait()The parent waits until the child process it created finishes

fork and exec are related to creating new processes, and wait is the command for a parent process to wait until the child process it created finishes. The examples are written with Python's os module. Python's os.fork(), os.wait() and os.execvp() directly call the operating system's system calls of the same name. (They work on macOS and Linux; Windows has no fork.)

fork: Duplicating a Process ​

fork() is used to create a new process. But the way it does this is a little unusual. Instead of starting a new program from the beginning, it duplicates itself exactly as it is running right now.

  • Analogy: it is like photocopying your homework, where even the line you were in the middle of writing gets copied. The copy does not start over from the beginning either; it continues from the exact line where the original stopped.
python
import os

print(f"pid : {os.getpid()}", flush=True)

rc = os.fork()          # the process splits in two here

if rc == 0:             # (1) child: fork() returns 0
    print(f"child (pid : {os.getpid()})", flush=True)
    os._exit(0)
else:                   # (2) parent: fork() returns the child's PID
    print(f"parent of {rc} (pid : {os.getpid()})", flush=True)

Output:

text
pid : 33045
parent of 33049 (pid : 33045)
child (pid : 33049)
  • The PID (Process ID) is a process's identification number. On UNIX-like systems, this number is used to give commands to a process. (The PID values change every time you run it.)
  • The moment fork() runs, one more process appears. The new process (the child) has an almost identical copy of the process that called fork (the parent).
  • The operating system sees two identical programs running, and both think "now it's time for fork() to return a value." So the child runs not from the beginning of the program, but from the line right after fork() finishes (the if statement). That is why the first line's pid : is printed only once.

How to Tell Parent and Child Apart: The Return Value ​

If they were perfectly identical copies, there would be no way to split up the work. The difference is the value fork() returns.

WhoValue returned by fork()
ParentThe PID of the newly created child (positive number)
Child0
On failure-1 in C (in Python, an OSError exception is raised)

Thanks to this difference, the parent and child can be made to do different things, as in if rc == 0:. It is a very useful approach.

The Execution Order Is Not Guaranteed ​

Which of the parent and child runs first cannot be known for sure (non-deterministic). That is decided by the CPU scheduler. So if you run the same code again, the child may print first, as below.

text
pid : 29146
child (pid : 29147)
parent of 29147 (pid : 29146)

Because It Is a Copy, Memory Is Separate ​

The child is a copy of the parent's memory, so when the child changes a variable, the parent's value does not change. This is different from threads, which share memory. (See Processes and Threads)

python
import os

count = 10

rc = os.fork()
if rc == 0:
    count += 1                      # the child changes its own copy
    print(f"child's count = {count}", flush=True)
    os._exit(0)
else:
    os.wait()
    print(f"parent's count = {count}")  # the parent's side is unchanged

Output:

text
child's count = 11
parent's count = 10

In reality, copying all the memory at the moment of fork() would be slow, so modern operating systems first let both share the same memory and copy a part only at the moment one side modifies it. This is called Copy-on-Write. The visible result is the same as above.

Watch Out: The Output Buffer Is Copied Too ​

Screen output usually does not go out right away; it collects in a temporary space called a buffer and goes out all at once. fork() copies this buffer too, so content still sitting in the buffer that had not been printed yet can be printed twice. That is why flush=True (empty the buffer right away) was added in the examples above.

python
import os

print("Hello", end="")      # no newline and no flush -> not on screen yet, only in the buffer

rc = os.fork()            # the buffer is copied along with everything else
if rc == 0:
    print(" / child")
else:
    os.wait()
    print(" / parent")

Output (when the output is sent through a pipe, as in python3 buf.py | cat):

text
Hello / child
Hello / parent

"Hello" was printed only once in the code, but it appears twice. The same goes for C's printf. When printing to a terminal, content can stay in the buffer if there is no newline (\n); when printing to a pipe or file, it can stay there even with a newline. So it is safe to empty the buffer with fflush(stdout) right before fork().

wait: Waiting Until the Child Finishes ​

wait() is the system call that makes the parent stop until the child process finishes. Let's add just one line, os.wait(), to the earlier example.

python
import os

print(f"pid : {os.getpid()}", flush=True)

rc = os.fork()

if rc == 0:
    print(f"child (pid : {os.getpid()})", flush=True)
    os._exit(0)
else:
    wc, status = os.wait()      # stops here until the child finishes
    print(f"parent of {rc} (wc : {wc} / pid : {os.getpid()})", flush=True)

Output:

text
pid : 33050
child (pid : 33054)
parent of 33054 (wc : 33054 / pid : 33050)
  • wait() returns the PID of the finished child (wc) and its exit status (status). That is why wc and rc have the same value.
  • Even if the parent gets the CPU first, wait() does not return until the child finishes. So the child's output always comes before the parent's last output. The problem of the unpredictable execution order can be tidied up with wait.
  • Analogy: it is like a parent sending a child on an errand and waiting at the front door. Only after the child comes back and says "I'm back (exit status)" does the parent move on to the next thing.

wait has one more important role. Even after the child finishes, the operating system keeps the child's information (PCB) instead of deleting it until the parent collects the exit status. A process that has finished but has not been collected yet is called a zombie process. It is cleaned up properly only when the parent collects it with wait. The PCB is covered in PCB and Context Switching.

exec: Switching to a Different Program ​

With only fork(), you could only run the same program as the parent multiple times. When you want the child to run a completely different program from the parent, you use exec.

python
import os

print(f"pid : {os.getpid()}", flush=True)

rc = os.fork()

if rc == 0:
    print(f"child (pid : {os.getpid()})", flush=True)
    # count the lines / words / characters in memo.txt with the wc command
    os.execvp("wc", ["wc", "memo.txt"])
    print("this shouldn't print out")   # never runs if exec succeeds
else:
    wc, status = os.wait()
    print(f"parent of {rc} (wc : {wc} / pid : {os.getpid()})", flush=True)

Output (memo.txt is a file with 3 lines, 6 words and 35 bytes):

text
pid : 33055
child (pid : 33059)
       3       6      35 memo.txt
parent of 33059 (wc : 33059 / pid : 33055)
  • execvp(program to run, argument list) finds the executable and overwrites the contents of the current process entirely with that program.
    • The new program's code is loaded into the code segment, and the data, heap and stack segments are also created anew to fit the new program. (See Memory Layout)
    • By convention, the first value in the argument list is the program name ("wc"), and what follows are the arguments actually passed ("memo.txt").
  • It does not create a new process. The PID stays the same (33059 above); only the work that process was doing changes to the wc program.
  • Since the original code is gone, the line after execvp() does not run. That is why "this shouldn't print out" was not printed. (Execution moves to the next line only if exec fails.)
  • Analogy: it is like the same actor (PID) staying on stage but swapping the script (program) for a completely different play.

fork + exec + wait = How a Shell Runs a Command ​

When you type ls in a terminal, the shell combines exactly these three.

text
Shell (parent)
  │ fork()  → duplicates itself to create a child
  ├─────────────────────────┐
  │                         │ child
  │ waits with wait()        │ exec("ls") → transforms into the ls program
  │                         │ runs ls, then exits
  │ ◀────────────────────────┘
  ▼
Shows the prompt for the next command

Because fork and exec are kept separate, the shell can do preparation work in between, such as redirecting the child's input and output (e.g. ls > out.txt).

Reference: The Original C Code ​

System calls are originally provided as C functions. Here is C code that behaves the same as the Python example above.

c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    printf("pid : %d\n", (int) getpid());
    fflush(stdout);                     // empty the output buffer before fork

    int rc = fork();
    if (rc < 0) {                       // fork failed
        exit(1);
    } else if (rc == 0) {               // child
        printf("child (pid : %d)\n", (int) getpid());
        fflush(stdout);                 // empty it before exec too (otherwise the output above may be lost)
        char *myargs[] = {"wc", "memo.txt", NULL};   // NULL marks the end
        execvp(myargs[0], myargs);
        printf("this shouldn't print out\n");        // does not run if exec succeeds
    } else {                            // parent
        int wc = wait(NULL);
        printf("parent of %d (wc : %d / pid : %d)\n", rc, wc, (int) getpid());
    }
    return 0;
}

Summary ​

ConceptPlain-language summary
System callThe official application form a program submits at the operating system's counter
User mode / Kernel modeThe customer area and the staff-only area. You cross into the staff area only during a system call
forkCopies the current process exactly, right down to the line it was on. The parent gets the child's PID, the child gets 0
Execution orderWhether the parent or child runs first is up to the scheduler
Copy-on-WriteShare first and copy only when something is modified, making fork fast
waitThe parent waits until the child finishes and cleans up (reaps) the finished child
Zombie processA process that has finished but has not yet been reaped by its parent
execKeeps the PID but swaps out the program contents entirely
fork + exec + waitThe basic sequence a shell uses to run one command