Skip to content

Linux Foundations / Manage a Linux host ยท Step 25 of 50

Lesson: How processes are createdSwitch
โ† Linux Foundations

System administration

How processes are created

Understand fork, exec, parents, children and the process tree.

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:

  1. 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.
  2. 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

bash
$ echo $$
2145
$ sleep 100 &
[1] 2290
$ ps -o pid,ppid,comm
    PID    PPID COMMAND
   2145    2144 bash
   2290    2145 sleep
   2291    2145 ps

Both 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.

bash
$ 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:

bash
exec sleep 5

Your 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.