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.

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.
Application (user mode)
│ calls fork(), read(), write() ...
▼
─────────────── Boundary (system call) ───────────────
▼
Kernel (kernel mode): does the actual work and returns the resultThis article covers three calls related to processes.
| System call | What 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.
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:
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 calledfork(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 afterfork()finishes (the if statement). That is why the first line'spid :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.
| Who | Value returned by fork() |
|---|---|
| Parent | The PID of the newly created child (positive number) |
| Child | 0 |
| 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.
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)
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 unchangedOutput:
child's count = 11
parent's count = 10In 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.
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):
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.
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:
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 whywcandrchave 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 withwait. - 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.
waithas 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 withwait. 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.
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):
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
wcprogram. - 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 ifexecfails.) - 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.
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 commandBecause 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.
#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
| Concept | Plain-language summary |
|---|---|
| System call | The official application form a program submits at the operating system's counter |
| User mode / Kernel mode | The customer area and the staff-only area. You cross into the staff area only during a system call |
| fork | Copies the current process exactly, right down to the line it was on. The parent gets the child's PID, the child gets 0 |
| Execution order | Whether the parent or child runs first is up to the scheduler |
| Copy-on-Write | Share first and copy only when something is modified, making fork fast |
| wait | The parent waits until the child finishes and cleans up (reaps) the finished child |
| Zombie process | A process that has finished but has not yet been reaped by its parent |
| exec | Keeps the PID but swaps out the program contents entirely |
| fork + exec + wait | The basic sequence a shell uses to run one command |
