fork()
Primer
- A fork refers to the way Unix creates new processes.
- Processes can refer to terminal commands, programs, games, etc.
- How it works is the parent process (already existing)
fork()
’s a child process (new one) and the child process receives a copy of the parents data.
- We end up with 2 processes when there was initially only one.
Process “Death”
- After a **child process “**dies” or finishes execution, it actually does not go away completely but it is stopped and no longer running i.e. dead / zombie.
- However, the kernel keeps a small remnant of this process in case the parent process picks up or starts again.
- Usually waits until the parent process calls
wait()
or waitpid()
to read the exit status i.e. wait for the child process to exit.
- When this happens, the remnant of the child process vanishes (from the process table).
- It also does not mean that once a child process dies, a parent process dies.
- But there are exceptions to this as well.
Normal Flow
- A child process that dies becomes a zombie until the parent process calls
wait()
or waitpid()
to read its exit status
- If the parent never calls
wait()
, the zombie sticks around (shows as <defunct>
in ps
).
Exception #1 - Ignoring SIGCHLD
SIGCHLD
is sent to a parent whenever one of its children dies.
- On some systems, if the parent tells the kernel "I’m ignoring SIGCHLD", the kernel automatically reaps the child
- This means that there is no zombie process left and no
wait()
is needed.
// Ignore the signal
signal(SIGCHLD, SIG_IGN)
Exception #2 — Parent dies first
- If the parent dies before the child finishes:
- The child gets re-parented to
init
(PID 1) — a special system process whose job includes cleaning up orphans (child processes with no parents).
- If the child later dies:
- On most systems,
init
will automatically wait()
for it → no zombie.
- On some systems,
init
might refuse to adopt already-defunct children and just kill them instantly.
Best Practices
- Call
wait()
for every child you fork()
- Explicitly ignore
SIGCHLD
if you don’t care about the exit status of the child process
The Full Process