On Linux, new processes come from existing ones. The process that creates another is the parent, and the new one is the child.
Fork, then exec
The classic way to start a program takes two steps:
- fork: the parent makes a copy of itself. The child gets a new PID and starts with a copy of the parent's memory, open file descriptors, environment and working directory.
- exec: the child replaces its program with a new one. The PID stays the same, but the code and data are now those of the new program.
Copying memory sounds expensive, but Linux uses copy-on-write. Parent and child share the same physical pages until one of them writes to a page.
When you type ls, the shell forks, the child execs /usr/bin/ls, and the shell usually waits for it to finish. Under the hood, Linux libraries often use the related clone system call to do the forking.
Watching parents and children
$ echo $$
2145
$ sleep 100 &
[1] 2290
$ ps -o pid,ppid,comm
PID PPID COMMAND
2145 2144 bash
2290 2145 sleep
2291 2145 psBoth sleep and ps have the shell as their parent.
The process tree
Follow the parents upward and you reach PID 1, the first user space process, started by the kernel at boot. On many distributions it is systemd. Others use OpenRC, runit or another init, and in a container PID 1 is often the application itself.
$ pstree -p 778
sshd(778)โโโsshd(2140)โโโsshd(2144)โโโbash(2145)โโโpstree(2300)pstree comes from the psmisc package, which may not be installed. ps -ef --forest draws a similar tree.
Replacing the shell
The shell has an exec builtin that skips the fork:
exec sleep 5Your shell becomes sleep. After five seconds it exits, and your terminal session may close with it, because there is no shell to return to. Try it only in a spare shell: run bash first, then exec.
This is useful at the end of a startup script. The final program takes over the script's PID, so signals sent to that PID reach the program directly.
Try it
Run bash to start a child shell. Compare echo $$ and echo $PPID, then run ps -ef --forest and find both shells. Type exit to return. You can do this in the processes and cron lab.
Check your understanding
How processes are created
All 4 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.