---
title: "Processes and System Calls"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 13
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 13 — Processes and System Calls

At the end of this chapter, a shell of sixty lines of C runs this script:

```
$ gcc -std=c17 -O2 -Wall -Wextra -o minish minish.c minish_parse.c -lm && ./minish
minish$ echo hello from a child process
hello from a child process
minish$ printf %s-%s\n left right
left-right
minish$ cd /usr
minish$ pwd
/usr
minish$ true
minish$ echo $?
```

***Output 13.1.** The chapter’s shell, `minish`, reading its first commands from a file. Some lines are left out.*

Typing `echo hello from a child process` in a shell looks like one action. It is at least two programs: the shell, which keeps running, and `echo`, which runs, prints and ends. Someone has to start `echo`, give it its words, wait for it, and learn whether it succeeded. Neither program can do this alone: starting a program, giving it memory, and writing to the screen are the work of the operating system’s kernel. This chapter is about the narrow door through which programs ask the kernel for things, and about the few requests that create and run [processes](#def-b2-processes-and-system-calls-process). Everything here is about Linux and other Unix-like systems; the tool `strace` used to watch the requests exists on Linux only.

**You already know.**

Book 2: a program is a file of instructions, a *[process](#def-b2-processes-and-system-calls-process)* is a program being run, with its own memory, the values of the registers when it last ran, the files it has opened, and a number given by the operating system, its *[process identifier](#def-b2-processes-and-system-calls-process)*; the operating system lets several [processes](#def-b2-processes-and-system-calls-process) share the processor. Book 2: the *kernel* is the part of the operating system that runs with full control of the hardware, and a program asks it for a service through a *[system call](#def-b2-processes-and-system-calls-syscall)*. Book 3, ch. 8: a shell reads a command line, cuts it into words, and runs the program the first word names with the others as *command-line arguments*; a command ends with an *exit status*, 0 for success; *environment variables* are name–value pairs passed to every program. Book 3: the memory of a C [process](#def-b2-processes-and-system-calls-process) holds code, global data, a heap and a stack. [Chapter 10](https://one-course.com/books/computer-science/4/en/chapter/10-assembly-language-and-the-calling-convention#ch-b2-assembly-and-calling-convention): `ecall` transfers control to the environment with a request number in `a7`.

## 13.1 The system call

**Definition 13.1 (User mode, kernel mode).**

A processor runs in *user mode* or in *kernel mode*. In user mode, the instructions that drive devices, change the memory map or stop the machine are refused, and only the memory the [process](#def-b2-processes-and-system-calls-process) was given is reachable. In kernel mode everything is allowed. The kernel of the operating system runs in kernel mode; every other program runs in user mode.

**Remark 13.2 (How a system call is made).**

Book 2’s [system call](#def-b2-processes-and-system-calls-syscall) is, at the level of the machine, a request from a user-mode program to the kernel. The program puts a request number and its arguments in registers and executes a special instruction (`ecall` on RISC-V, `syscall` on x86-64), which switches the processor to [kernel mode](#def-b2-processes-and-system-calls-modes) and jumps to a fixed entry point in the kernel; the kernel checks the request, does the work, puts the result in a register, and returns to [user mode](#def-b2-processes-and-system-calls-modes) just after the instruction.

The C library wraps each [system call](#def-b2-processes-and-system-calls-syscall) in a function of the same name: `write(fd, buffer, n)` asks the kernel to write $n$ bytes to the open file numbered `fd`, and descriptor 1 is the standard output. `printf` is a different kind of function, a *library call*: it formats its text in the program’s own memory, keeps it in a buffer, and calls `write` later, when the buffer is full, at a newline on a terminal, or when the program ends.

```c
int main(void)
{
    printf("hello, library\n");             /* a library call: kept in a buffer for now */
    ssize_t n = write(1, "hello, kernel\n", 14);   /* a system call: descriptor 1, 14 bytes */
    return n == 14 ? 0 : 1;                 /* returning from main flushes the buffer */
}
```

***Listing 13.1.** One line through the library, one straight to the kernel code/bachelor-2/13-processes-and-system-calls/listings/hello_write.c*

```
$ gcc -o hello hello_write.c
$ ./hello
hello, kernel
hello, library
$ strace -qq -e trace=write,exit_group ./hello > /dev/null
write(1, "hello, kernel\n", 14)         = 14
write(1, "hello, library\n", 15)        = 15
exit_group(0)                           = ?
```

***Output 13.2.** The program, then its `write` and `exit_group` [system calls](#def-b2-processes-and-system-calls-syscall) as `strace` reports them.*

The “library” line comes second. On a terminal `printf` would have flushed it at the newline; here the output is not a terminal, so the line waits in the buffer until `main` returns, while the `write` went to the kernel at once. `strace` runs a program and prints each of its [system calls](#def-b2-processes-and-system-calls-syscall) with its arguments and result: two `write`s, of 14 and 15 bytes, and `exit_group`, the call that ends the [process](#def-b2-processes-and-system-calls-process), which has no result since it never returns.

![The path of a write. The program calls an ordinary library function, which executes the system-call instruction; the processor switches to kernel mode at a fixed entry point, where the kernel checks the descriptor and the buffer before doing the work. The result returns in a register, in user mode.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-processes-and-system-calls/fig-557bbd4b35bd.svg)

*The path of a `write`. The program calls an ordinary library function, which executes the system-call instruction; the processor switches to [kernel mode](#def-b2-processes-and-system-calls-modes) at a fixed entry point, where the kernel checks the descriptor and the buffer before doing the work. The result returns in a register, in [user mode](#def-b2-processes-and-system-calls-modes).*

The crossing is not free: the processor changes mode, saves and restores state, and the kernel checks every argument. A measurement compares a call of an ordinary function with the cheapest [system call](#def-b2-processes-and-system-calls-syscall), `getppid`, which only reads a number the kernel keeps:

```c
    long sum = 0;
    double t0 = now_ns();
    for (long k = 0; k < CALLS; k++)
        sum += parent_of(k);
    double t1 = now_ns();
    for (long k = 0; k < CALLS; k++)
        sum += syscall(SYS_getppid);                      /* into the kernel and back */
    double t2 = now_ns();
```

***Listing 13.2.** Two million calls of each kind code/bachelor-2/13-processes-and-system-calls/listings/syscall_cost.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o syscall_cost syscall_cost.c -lm && ./syscall_cost
function call:    0.3 ns
system call:     71.5 ns, 217 times longer
```

***Output 13.3.** One run on the author’s laptop, compiled with `-O2`.*

A [system call](#def-b2-processes-and-system-calls-syscall) costs here about two hundred function calls. That is the reason for `printf`’s buffer: a program that printed a thousand lines with one `write` each would make a thousand crossings instead of three ([Exercise 13.11](#exo-b2-processes-and-system-calls-11)).

## 13.2 Creating a process: fork

**Remark 13.3 (What the kernel keeps for a process).**

Book 2’s [process](#def-b2-processes-and-system-calls-process) is, for the kernel, a running program together with the resources it keeps for it: its memory, its registers when it is not running, its open files, and also its working directory and its environment. The [process identifier](#def-b2-processes-and-system-calls-process) (PID) is a positive integer unique among the [processes](#def-b2-processes-and-system-calls-process) alive at the same time; a number freed by a [process](#def-b2-processes-and-system-calls-process) that has ended may be given to a later one.

**Definition 13.4 (Parent, child, process tree).**

A [process](#def-b2-processes-and-system-calls-process) that creates another is its *parent*, and the created one its *child*. Since every [process](#def-b2-processes-and-system-calls-process) but the first is created by another, the [processes](#def-b2-processes-and-system-calls-process) form a *process tree*, rooted at the first [process](#def-b2-processes-and-system-calls-process) the kernel starts.

**Definition 13.5 (Fork).**

A *fork* creates a new [process](#def-b2-processes-and-system-calls-process) by duplicating the caller. The [system call](#def-b2-processes-and-system-calls-syscall) `fork()` makes a [child](#def-b2-processes-and-system-calls-tree) whose memory is a copy of the [parent](#def-b2-processes-and-system-calls-tree)’s, with the same open files and working directory, and both [processes](#def-b2-processes-and-system-calls-process) continue from the return of `fork`. It returns 0 in the [child](#def-b2-processes-and-system-calls-tree) and the [child](#def-b2-processes-and-system-calls-tree)’s PID in the [parent](#def-b2-processes-and-system-calls-tree), or $-1$ in the [parent](#def-b2-processes-and-system-calls-tree), with no [child](#def-b2-processes-and-system-calls-tree), if it fails.

One call, two returns: the only way for the code to know which [process](#def-b2-processes-and-system-calls-process) it is running in is the value `fork` returned. The copy is real: a variable changed in the [child](#def-b2-processes-and-system-calls-tree) keeps its old value in the [parent](#def-b2-processes-and-system-calls-tree).

```c
    int books = 10;
    pid_t me = getpid();
    pid_t r = fork();                        /* from here on, two processes run this code */
    if (r < 0) {
        perror("fork");
        return 1;
    }
    if (r == 0) {                            /* the child */
        books = 20;                          /* changes the child's copy only */
        printf("child:  fork returned 0; my parent is the caller: %s; books = %d\n",
               getppid() == me ? "yes" : "no", books);
        return 0;
    }
    pid_t done = waitpid(r, NULL, 0);        /* the parent waits for its child */
    printf("parent: fork returned my child's number: %s; books = %d\n",
           done == r ? "yes" : "no", books);
    return 0;
```

***Listing 13.3.** Two [processes](#def-b2-processes-and-system-calls-process), one program code/bachelor-2/13-processes-and-system-calls/listings/fork_basic.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o fork_basic fork_basic.c -lm && ./fork_basic
child:  fork returned 0; my parent is the caller: yes; books = 20
parent: fork returned my child's number: yes; books = 10
```

***Output 13.4.** Each [process](#def-b2-processes-and-system-calls-process) learns its role from the value of `fork`.*

The program prints relations, never the numbers themselves, because PIDs change from one run to the next. `waitpid`, the subject of [Section 13.4](#sec-13-4), makes the [parent](#def-b2-processes-and-system-calls-tree) wait until the [child](#def-b2-processes-and-system-calls-tree) has ended, which fixes the order of the two lines. Linux does not copy the memory at the moment of the [fork](#def-b2-processes-and-system-calls-fork): the two [processes](#def-b2-processes-and-system-calls-process) share the pages, marked read-only, and a page is copied only when one of them writes to it. The program cannot tell the difference, and a [fork](#def-b2-processes-and-system-calls-fork) followed at once by an `exec` copies almost nothing.

![A fork of fork_basic.c. The two address spaces start equal, except for the value fork returned; the child’s assignment books = 20 does not reach the parent.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-processes-and-system-calls/fig-ff9f30517343.svg)

*A [fork](#def-b2-processes-and-system-calls-fork) of `fork_basic.c`. The two address spaces start equal, except for the value `fork` returned; the [child](#def-b2-processes-and-system-calls-tree)’s assignment `books = 20` does not reach the [parent](#def-b2-processes-and-system-calls-tree).*

A [process](#def-b2-processes-and-system-calls-process) that calls `fork` several times, with its children doing the same, grows a tree. In `fork_tree.c` each [process](#def-b2-processes-and-system-calls-process) names itself `p` followed by the indices of the [forks](#def-b2-processes-and-system-calls-fork) it came out of as the [child](#def-b2-processes-and-system-calls-tree), and the [parent](#def-b2-processes-and-system-calls-tree) waits for each [child](#def-b2-processes-and-system-calls-tree), so that each subtree finishes before the next [fork](#def-b2-processes-and-system-calls-fork):

```c
int main(void)
{
    char name[16] = "p";
    for (int i = 0; i < 3; i++) {
        pid_t r = fork();
        if (r == 0) {                                   /* the child extends its name */
            size_t n = strlen(name);
            name[n] = (char)('0' + i);
            name[n + 1] = '\0';
        } else {
            waitpid(r, NULL, 0);                        /* the child's whole subtree first */
        }
    }
    printf("%-5s depth %zu\n", name, strlen(name) - 1);  /* one digit per fork it came from */
    fflush(stdout);
    return 0;
}
```

***Listing 13.4.** Three [forks](#def-b2-processes-and-system-calls-fork) in a row code/bachelor-2/13-processes-and-system-calls/listings/fork_tree.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o fork_tree fork_tree.c -lm && ./fork_tree
p012  depth 3
p01   depth 2
p02   depth 2
p0    depth 1
p12   depth 2
p1    depth 1
p2    depth 1
p     depth 0
```

***Output 13.5.** Eight [processes](#def-b2-processes-and-system-calls-process); each prints after its children.*

![The process tree of fork_tree.c: an edge goes from a parent to a child. The fork of index i is made by every process alive at that moment, and doubles their number.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-processes-and-system-calls/fig-7e2733891710.svg)

*The [process tree](#def-b2-processes-and-system-calls-tree) of `fork_tree.c`: an edge goes from a [parent](#def-b2-processes-and-system-calls-tree) to a [child](#def-b2-processes-and-system-calls-tree). The [fork](#def-b2-processes-and-system-calls-fork) of index $i$ is made by every [process](#def-b2-processes-and-system-calls-process) alive at that moment, and doubles their number.*

**Proposition 13.6 (Counting forks).**

If a [process](#def-b2-processes-and-system-calls-process) executes $n$ successive `fork` calls, and every [process](#def-b2-processes-and-system-calls-process) created continues from the same point and executes the remaining calls, then $2^n$ [processes](#def-b2-processes-and-system-calls-process) exist at the end, counting the first.

The proof is [Exercise 13.8](#exo-b2-processes-and-system-calls-8). With $n = 3$ the output has eight lines, and the depth of each [process](#def-b2-processes-and-system-calls-process), the number of [forks](#def-b2-processes-and-system-calls-fork) it came out of as the [child](#def-b2-processes-and-system-calls-tree), takes the value $d$ for $\binom{3}{d}$ of them.

## 13.3 Running a program: exec

A [fork](#def-b2-processes-and-system-calls-fork) makes a copy of the same program. To run another one, a [process](#def-b2-processes-and-system-calls-process) replaces its own program.

**Definition 13.7 (Exec, argument vector).**

An *exec* replaces the program of the calling [process](#def-b2-processes-and-system-calls-process) by a new one, read from a file: the code, data, heap and stack are discarded and rebuilt, and the new program starts at its beginning, in the same [process](#def-b2-processes-and-system-calls-process), with the same PID, open files and working directory. Its arguments are given as an *argument vector*, an array of strings ending with a null pointer, whose element 0 is by convention the program’s name; it becomes `argv` in the new program’s `main`. A successful exec does not return; if it returns, it failed.

The C library offers several front ends to the one [system call](#def-b2-processes-and-system-calls-syscall) `execve(path, argv, envp)`: `execvp` searches the directories of the `PATH` variable for the program and keeps the environment; `execlp` takes the arguments one by one; `execve` itself takes a full path and a new environment.

```c
    printf("exec_demo: three programs follow\n");
    fflush(stdout);                                  /* or the line dies with the old image */
    pid_t r = fork();
    if (r == 0) {
        char *argv[] = {"echo", "two words", "three", NULL};
        execvp("echo", argv);                        /* searched for in the PATH */
        perror("execvp");                            /* reached only if exec failed */
        _exit(127);
    }
    waitpid(r, NULL, 0);
    if (fork() == 0) {
        char *argv[] = {"env", NULL};
        char *envp[] = {"LIBRARY=town", "OPENS=9", NULL};
        execve("/usr/bin/env", argv, envp);          /* a full path, and a new environment */
        perror("execve");
        _exit(127);
    }
    wait(NULL);
    execlp("printf", "printf", "%s+%s\n", "a", "b", (char *)NULL);   /* this process itself */
    printf("this line is never printed\n");
    return 1;
```

***Listing 13.5.** Three [execs](#def-b2-processes-and-system-calls-exec): in two children, then in the [process](#def-b2-processes-and-system-calls-process) itself code/bachelor-2/13-processes-and-system-calls/listings/exec_demo.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exec_demo exec_demo.c -lm && ./exec_demo
exec_demo: three programs follow
two words three
LIBRARY=town
OPENS=9
a+b
```

***Output 13.6.** Each line after the first comes from another program.*

`echo` receives `"two words"` as one argument: no shell cut it, the vector is passed as it is. `env`, started with an environment of two variables, prints exactly those. The last [exec](#def-b2-processes-and-system-calls-exec) replaces `exec_demo` itself by `printf`, so the line after it is never printed, and the exit status of the [process](#def-b2-processes-and-system-calls-process) is `printf`’s. The `fflush` at the top matters for the same reason: an [exec](#def-b2-processes-and-system-calls-exec) discards the memory of the old program, buffer included, and a line still waiting in `printf`’s buffer would be lost.

## 13.4 Waiting for a child

**Definition 13.8 (Waiting for a child).**

A [process](#def-b2-processes-and-system-calls-process) *waits for a child* with `waitpid(pid, &status, 0)`, which blocks until that [child](#def-b2-processes-and-system-calls-tree) has ended and returns its PID; `wait(&status)` does the same for any [child](#def-b2-processes-and-system-calls-tree). The integer `status` encodes how the [child](#def-b2-processes-and-system-calls-tree) ended: `WIFEXITED(status)` is true when it ended by returning from `main` or calling `exit`, and `WEXITSTATUS(status)` is then the low 8 bits of its exit status; `WIFSIGNALED(status)` is true when a signal killed it, and `WTERMSIG(status)` is the signal’s number.

```c
static void report(const char *what, int status)
{
    if (WIFEXITED(status))
        printf("%-22s exited with status %d\n", what, WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
        printf("%-22s killed by signal %d (%s)\n", what, WTERMSIG(status),
               strsignal(WTERMSIG(status)));
}
```

***Listing 13.6.** Reading a status code/bachelor-2/13-processes-and-system-calls/listings/wait_status.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o wait_status wait_status.c -lm && ./wait_status
return 0 from main     exited with status 0
exit(3)                exited with status 3
raise(SIGTERM)         killed by signal 15 (Terminated)
exit(300)              exited with status 44
```

***Output 13.7.** Four children, four endings.*

Signals are the subject of [Chapter 14](https://one-course.com/books/computer-science/4/en/chapter/14-files-pipes-and-signals#ch-b2-files-pipes-signals); here it is enough that `raise(SIGTERM)` sends the [process](#def-b2-processes-and-system-calls-process) the “terminate” signal, number 15, whose default effect is to end it. `exit(300)` gives 44, the low 8 bits of 300: an exit status is a number from 0 to 255. Shells report a death by signal $n$ as the status $128 + n$, so that one number covers both cases.

Between its end and its [parent](#def-b2-processes-and-system-calls-tree)’s wait, a [child](#def-b2-processes-and-system-calls-tree) is in a peculiar state: its program, memory and files are gone, but the kernel must keep its status until the [parent](#def-b2-processes-and-system-calls-tree) asks for it.

**Definition 13.9 (Zombie, orphan).**

A *zombie* is a [process](#def-b2-processes-and-system-calls-process) that has ended but whose [parent](#def-b2-processes-and-system-calls-tree) has not yet waited for it: only its entry in the kernel’s [process](#def-b2-processes-and-system-calls-process) table remains, with its PID and its status. An *orphan* is a [process](#def-b2-processes-and-system-calls-process) whose [parent](#def-b2-processes-and-system-calls-tree) has ended before it; the kernel gives it a new [parent](#def-b2-processes-and-system-calls-tree), the first [process](#def-b2-processes-and-system-calls-process) or a [process](#def-b2-processes-and-system-calls-process) that asked to adopt orphans, which waits for it when it ends.

On Linux the kernel shows each [process](#def-b2-processes-and-system-calls-process) as a directory `/proc/<pid>`, whose file `status` has a line `State:`, with `Z` for a [zombie](#def-b2-processes-and-system-calls-zombie). `zombie.c` reads that letter for a [child](#def-b2-processes-and-system-calls-tree) that has ended, before and after waiting for it, then makes an [orphan](#def-b2-processes-and-system-calls-zombie): a middle [process](#def-b2-processes-and-system-calls-process) starts a grandchild and ends at once, and the grandchild watches its own [parent](#def-b2-processes-and-system-calls-tree) change.

```c
    pid_t r = fork();
    if (r == 0) _exit(0);                            /* the child ends at once */
    while (state(r) != 'Z')                          /* until the kernel has marked it */
        nap();
    printf("child ended, not yet waited for: state %c\n", state(r));
    waitpid(r, NULL, 0);
    printf("after waitpid:                   state %c\n", state(r));
```

***Listing 13.7.** A [child](#def-b2-processes-and-system-calls-tree) ended, not yet waited for code/bachelor-2/13-processes-and-system-calls/listings/zombie.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o zombie zombie.c -lm && ./zombie
child ended, not yet waited for: state Z
after waitpid:                   state -
the grandchild outlived its parent and was adopted by another process
```

***Output 13.8.** A [zombie](#def-b2-processes-and-system-calls-zombie), then nothing; an [orphan](#def-b2-processes-and-system-calls-zombie), adopted.*

After the wait, `/proc` has no entry any more: the letter `-` is the program’s way of saying so. A long-running [parent](#def-b2-processes-and-system-calls-tree) that never waits accumulates [zombies](#def-b2-processes-and-system-calls-zombie), each holding a PID, and PIDs are a finite resource ([Exercise 13.2](#exo-b2-processes-and-system-calls-2)).

![The states of a process, with the zombie state. Book 2’s ready, running and blocked states remain; ending leads to the zombie state, and only the parent’s wait removes the process.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-processes-and-system-calls/fig-332e3984d77e.svg)

*The states of a [process](#def-b2-processes-and-system-calls-process), with the [zombie](#def-b2-processes-and-system-calls-zombie) state. Book 2’s ready, running and blocked states remain; ending leads to the [zombie](#def-b2-processes-and-system-calls-zombie) state, and only the [parent](#def-b2-processes-and-system-calls-tree)’s wait removes the [process](#def-b2-processes-and-system-calls-process).*

## 13.5 A minimal shell

The four calls are all a shell needs, with one more notion.

**Definition 13.10 (Built-in command).**

A *built-in command* is a command that the shell carries out itself, in its own [process](#def-b2-processes-and-system-calls-process), instead of running a program in a [child](#def-b2-processes-and-system-calls-tree).

The shell’s main loop:

**Method 13.11 (The shell’s loop).**

Repeat until the input ends or the command is `exit`:

1. print a prompt and read one line;
2. cut it into words; an empty line is skipped;
3. if the first word names a [built-in command](#def-b2-processes-and-system-calls-builtin) , run it in the shell itself;
4. otherwise [fork](#def-b2-processes-and-system-calls-fork) ; in the [child](#def-b2-processes-and-system-calls-tree) , [exec](#def-b2-processes-and-system-calls-exec) the program the first word names with the words as its [argument vector](#def-b2-processes-and-system-calls-exec) , and if the [exec](#def-b2-processes-and-system-calls-exec) fails, report it and end the [child](#def-b2-processes-and-system-calls-tree) with status 127;
5. in the [parent](#def-b2-processes-and-system-calls-tree) , wait for the [child](#def-b2-processes-and-system-calls-tree) , and keep its status for the next `$?` .

![The loop of . Only the parent goes round again; the child either becomes the command or ends.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-processes-and-system-calls/fig-c4a53b3b9d15.svg)

*The loop of [Method 13.11](#met-b2-processes-and-system-calls-shell-loop). Only the [parent](#def-b2-processes-and-system-calls-tree) goes round again; the [child](#def-b2-processes-and-system-calls-tree) either becomes the command or ends.*

The splitting is a separate file, so that it can be tested alone. It cuts the line in place, at blanks, and points each word of the vector into the line; the word `$?` becomes the last status.

```c
int split(char *line, char **argv, int max, int last)
{
    static char status[12];
    int argc = 0;
    for (char *w = strtok(line, " \t\n"); w && argc < max; w = strtok(NULL, " \t\n")) {
        if (strcmp(w, "$?") == 0) {
            snprintf(status, sizeof status, "%d", last);
            w = status;
        }
        argv[argc++] = w;                     /* a pointer into the line itself */
    }
    argv[argc] = NULL;                        /* exec wants a null pointer at the end */
    return argc;
}
```

***Listing 13.8.** Cutting a line into words code/bachelor-2/13-processes-and-system-calls/listings/minish_parse.c*

```c
static int run(char **argv)                   /* an external command: its exit status */
{
    pid_t r = fork();
    if (r < 0) {
        perror("minish: fork");
        return 1;
    }
    if (r == 0) {                             /* the child becomes the command */
        execvp(argv[0], argv);
        fprintf(stderr, "minish: %s: command not found\n", argv[0]);
        _exit(127);                           /* never return into the shell's loop */
    }
    int status;
    if (waitpid(r, &status, 0) < 0)
        return 1;
    return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
```

***Listing 13.9.** An external command: [fork](#def-b2-processes-and-system-calls-fork), [exec](#def-b2-processes-and-system-calls-exec), wait code/bachelor-2/13-processes-and-system-calls/listings/minish.c*

```c
int main(void)
{
    char line[1024], *argv[MAXARGS + 1];
    int last = 0;
    for (;;) {
        printf("minish$ ");
        if (!fgets(line, sizeof line, stdin))
            break;                            /* end of input: leave like exit */
        if (!isatty(0))
            fputs(line, stdout);              /* a script: show the line as if typed */
        fflush(stdout);                       /* before fork: the prompt before the output */
        int argc = split(line, argv, MAXARGS, last);
        if (argc == 0)
            continue;
        if (strcmp(argv[0], "exit") == 0)
            return argc > 1 ? atoi(argv[1]) : last;
        last = strcmp(argv[0], "cd") == 0 ? cd(argc, argv) : run(argv);
    }
    printf("\n");
    return last;
}
```

***Listing 13.10.** The loop code/bachelor-2/13-processes-and-system-calls/listings/minish.c*

The `_exit(127)` after a failed [exec](#def-b2-processes-and-system-calls-exec) is essential. Without it the [child](#def-b2-processes-and-system-calls-tree) returns from `run` into the shell’s loop, and two shells read the same input from then on ([Exercise 13.6](#exo-b2-processes-and-system-calls-6)). It is `_exit`, not `exit`, so that the [child](#def-b2-processes-and-system-calls-tree) does not flush a copy of the [parent](#def-b2-processes-and-system-calls-tree)’s buffers. Here is the end of the hook’s script:

```
0
minish$ false
minish$ echo $?
1
minish$ no-such-command
minish: no-such-command: command not found
minish$ echo $?
127
minish$ cd /no/such/place
minish: cd: /no/such/place: cannot go there
minish$ echo $?
1
minish$ exit 3
[exit status 3]
```

***Output 13.9.** The rest of the script: statuses, a missing command, a failed `cd`. Some lines are left out.*

Why are `cd` and `exit` built in? `exit` must end the shell, not a [child](#def-b2-processes-and-system-calls-tree). For `cd`, the reason is a theorem about [processes](#def-b2-processes-and-system-calls-process).

**Proposition 13.12 (A child cannot move its parent).**

A change of working directory made by a [process](#def-b2-processes-and-system-calls-process) after a `fork` has no effect on the working directory of its [parent](#def-b2-processes-and-system-calls-tree). Hence a shell’s `cd` that changes the shell’s own directory must be built in.

**Proof.** The working directory is part of each [process](#def-b2-processes-and-system-calls-process)’s state, which `fork` copies ([Definition 13.5](#def-b2-processes-and-system-calls-fork)). `chdir` changes the working directory of the [process](#def-b2-processes-and-system-calls-process) that calls it only; the copy in the [parent](#def-b2-processes-and-system-calls-tree) is a separate value, which no call of the [child](#def-b2-processes-and-system-calls-tree) touches. If `cd` were a program, the shell would [fork](#def-b2-processes-and-system-calls-fork) a [child](#def-b2-processes-and-system-calls-tree) and the [child](#def-b2-processes-and-system-calls-tree), after its [exec](#def-b2-processes-and-system-calls-exec), would change its own directory and end, leaving the shell where it was. ∎

```c
    if (fork() == 0) {
        if (chdir("/") != 0 || !getcwd(there, sizeof there)) _exit(1);
        printf("child:  now in %s\n", there);
        fflush(stdout);                              /* _exit does not flush the buffer */
        _exit(0);
    }
    wait(NULL);
    if (!getcwd(after, sizeof after)) return 1;
    printf("parent: still where it was: %s\n", strcmp(before, after) == 0 ? "yes" : "no");
```

***Listing 13.11.** A [child](#def-b2-processes-and-system-calls-tree) moves code/bachelor-2/13-processes-and-system-calls/listings/cd_child.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o cd_child cd_child.c -lm && ./cd_child
child:  now in /
parent: still where it was: yes
```

***Output 13.10.** Its [parent](#def-b2-processes-and-system-calls-tree) does not.*

The same proposition explains why a script run as a program, `./setup.sh`, cannot change the directory of the shell that started it: the script runs in a [child](#def-b2-processes-and-system-calls-tree) shell.

**In practice — Real shells.**

A real shell adds quoting, variables, redirections and pipes (the next chapter’s subject), jobs that run in the background, and dozens of built-ins: `export`, `source` and `umask` must be built in for the reason of [Proposition 13.12](#prop-b2-processes-and-system-calls-cd-builtin), others such as `echo` only for speed. Its heart is still the loop of [Method 13.11](#met-b2-processes-and-system-calls-shell-loop). [Processes](#def-b2-processes-and-system-calls-process) are also the way servers isolate work: a web server that [forks](#def-b2-processes-and-system-calls-fork) a worker per task gets, from the kernel, a worker that cannot corrupt the others’ memory.

## 13.6 Exercises

**Exercise 13.1 ★.**

How many lines does this program print? Draw its [process tree](#def-b2-processes-and-system-calls-tree).

```c
int main(void)
{
    fork();
    fork();
    printf("hello\n");
    return 0;
}
```

***Listing 13.12.** Two [forks](#def-b2-processes-and-system-calls-fork), one `printf` code/bachelor-2/13-processes-and-system-calls/listings/exo_count.c*

**Solution of Exercise 13.1.**

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_count exo_count.c -lm && ./exo_count
hello
hello
hello
hello
```

***Output 13.15.** Four lines.*

The first `fork` makes two [processes](#def-b2-processes-and-system-calls-process); both execute the second, which makes four, and each of the four prints once. The tree: the original [process](#def-b2-processes-and-system-calls-process) has two children, made by the first and the second [fork](#def-b2-processes-and-system-calls-fork); its first [child](#def-b2-processes-and-system-calls-tree) has one [child](#def-b2-processes-and-system-calls-tree) of its own, made by the second [fork](#def-b2-processes-and-system-calls-fork); the two others have none.

**Exercise 13.2 ★.**

This [parent](#def-b2-processes-and-system-calls-tree) never waits. Explain the output, what remains of each [child](#def-b2-processes-and-system-calls-tree), and when it would disappear.

```c
int main(void)
{
    for (int k = 0; k < 3; k++)
        if (fork() == 0)
            _exit(0);                                /* each child ends at once */
    struct timespec t = {0, 1000000};
    while (zombies() < 3)
        nanosleep(&t, NULL);
    printf("3 children ended, %d of them still in the process table\n", zombies());
    return 0;
}
```

***Listing 13.13.** Three children, no `wait` code/bachelor-2/13-processes-and-system-calls/listings/exo_nowait.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_nowait exo_nowait.c -lm && ./exo_nowait
3 children ended, 3 of them still in the process table
```

***Output 13.11.** Counted from `/proc`.*

**Solution of Exercise 13.2.**

Each [child](#def-b2-processes-and-system-calls-tree) ends at once, but its [parent](#def-b2-processes-and-system-calls-tree) never waits: the kernel keeps its entry in the [process](#def-b2-processes-and-system-calls-process) table, with its PID and its exit status, in case the [parent](#def-b2-processes-and-system-calls-tree) asks. The program counts the three, all in state `Z`. They disappear when the [parent](#def-b2-processes-and-system-calls-tree) waits for them or when the [parent](#def-b2-processes-and-system-calls-tree) itself ends: they then become [orphans](#def-b2-processes-and-system-calls-zombie), adopted by a [process](#def-b2-processes-and-system-calls-process) that waits for them at once. A server that [forks](#def-b2-processes-and-system-calls-fork) a [child](#def-b2-processes-and-system-calls-tree) per request and never waits would fill the [process](#def-b2-processes-and-system-calls-process) table with [zombies](#def-b2-processes-and-system-calls-zombie), until `fork` fails for lack of PIDs.

**Exercise 13.3 ★.**

Write `runit`, a program that runs the command given on its own command line and exits with that command’s status, reported as a shell would: `runit false` exits with 1, `runit sh -c 'kill $$'` with 143, and a missing command with 127.

**Solution of Exercise 13.3.**

```c
int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: runit command [argument...]\n");
        return 2;
    }
    pid_t r = fork();
    if (r < 0) {
        perror("runit: fork");
        return 1;
    }
    if (r == 0) {
        execvp(argv[1], argv + 1);                /* argv + 1 ends with argv's null pointer */
        perror("runit: exec");
        _exit(127);
    }
    int status;
    if (waitpid(r, &status, 0) < 0)
        return 1;
    if (WIFEXITED(status))
        return WEXITSTATUS(status);
    return 128 + WTERMSIG(status);                /* killed by signal n: 128 + n */
}
```

*Running the command line’s command code/bachelor-2/13-processes-and-system-calls/exercises/runit.c*

`argv + 1` is already an [argument vector](#def-b2-processes-and-system-calls-exec): it starts at the command’s name and ends with `argv`’s null pointer. The test checks `true`, `false`, `exit 42`, a shell that kills itself with signal 15 (status 143) and a missing command (127).

**Exercise 13.4 ★.**

A loop `for (int i = 0; i < n; i++) fork();` runs in one [process](#def-b2-processes-and-system-calls-process), and nobody waits. How many [processes](#def-b2-processes-and-system-calls-process) are created by the loop? How many times is `fork` called in all? How many of the final [processes](#def-b2-processes-and-system-calls-process) have no children?

**Solution of Exercise 13.4.**

The [process](#def-b2-processes-and-system-calls-process) that runs iteration $i$ of the loop, counting from 0, executes the remaining calls; by [Proposition 13.6](#prop-b2-processes-and-system-calls-fork-count), $2^n$ [processes](#def-b2-processes-and-system-calls-process) exist at the end, so the loop created $2^n - 1$. Each successful call creates exactly one [process](#def-b2-processes-and-system-calls-process), so `fork` was called $2^n - 1$ times. A [process](#def-b2-processes-and-system-calls-process) created at iteration $i$ makes one [child](#def-b2-processes-and-system-calls-tree) at each of the iterations $i + 1, \dots, n - 1$: it has none exactly when $i = n - 1$. There are $2^{n-1}$ [processes](#def-b2-processes-and-system-calls-process) alive just before the last iteration, so $2^{n-1}$ are created by it: half of the final [processes](#def-b2-processes-and-system-calls-process) have no children.

**Exercise 13.5 ★★.**

In which order are the letters printed? Could another order appear on another run?

```c
int main(void)
{
    say("A");
    pid_t r = fork();
    if (r == 0) {
        say("B");
        if (fork() == 0) {
            say("C");
            return 0;
        }
        wait(NULL);
        say("D");
        return 0;
    }
    waitpid(r, NULL, 0);
    say("E");
    if (fork() == 0) {
        say("F");
        return 0;
    }
    wait(NULL);
    say("G\n");
    return 0;
}
```

***Listing 13.14.** Letters from three [processes](#def-b2-processes-and-system-calls-process) code/bachelor-2/13-processes-and-system-calls/listings/exo_order.c*

**Solution of Exercise 13.5.**

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_order exo_order.c -lm && ./exo_order
ABCDEFG
```

***Output 13.16.** The letters in order.*

`ABCDEFG`, on every run. Each letter is printed after the previous one, because of a [fork](#def-b2-processes-and-system-calls-fork) or a wait: A comes before the first [fork](#def-b2-processes-and-system-calls-fork); B is printed by the [child](#def-b2-processes-and-system-calls-tree); C by the grandchild, created after B; D by the [child](#def-b2-processes-and-system-calls-tree) after it has waited for the grandchild; E by the [parent](#def-b2-processes-and-system-calls-tree) after waiting for the [child](#def-b2-processes-and-system-calls-tree); F by a second [child](#def-b2-processes-and-system-calls-tree) created after E; G after waiting for it. Every `say` flushes, so no letter is left in a buffer that a [fork](#def-b2-processes-and-system-calls-fork) would copy.

**Exercise 13.6 ★★.**

This program runs three commands, but a failed [exec](#def-b2-processes-and-system-calls-exec) is not followed by `_exit`. Explain every line of its output.

```c
int main(void)
{
    char *commands[] = {"true", "no-such-command", "true"};
    for (int k = 0; k < 3; k++) {
        printf("running %s\n", commands[k]);
        fflush(stdout);
        if (fork() == 0) {
            char *argv[] = {commands[k], NULL};
            execvp(commands[k], argv);
            printf("exec of %s failed\n", commands[k]);   /* and then? */
        } else {
            wait(NULL);
        }
    }
    printf("done\n");
    return 0;
}
```

***Listing 13.15.** A missing `_exit` code/bachelor-2/13-processes-and-system-calls/listings/exo_noexit.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_noexit exo_noexit.c -lm && ./exo_noexit
running true
running no-such-command
exec of no-such-command failed
running true
done
running true
done
```

***Output 13.12.** One `done` too many.*

**Solution of Exercise 13.6.**

The [parent](#def-b2-processes-and-system-calls-tree) prints `running true`, runs `true` in a [child](#def-b2-processes-and-system-calls-tree) and waits. Then it announces the missing command; the [child](#def-b2-processes-and-system-calls-tree)’s `execvp` fails, and the [child](#def-b2-processes-and-system-calls-tree) prints `exec of no-such-command failed` and then, instead of ending, goes on with the loop: it is a second copy of the program at $k = 2$. It prints `running true`, runs `true` in a [child](#def-b2-processes-and-system-calls-tree) of its own, prints `done` and ends. Only then does the [parent](#def-b2-processes-and-system-calls-tree)’s `wait` return; the [parent](#def-b2-processes-and-system-calls-tree) goes on with $k = 2$ too, and prints `running true` and `done` again. In a shell the same bug makes two shells read the same input. The fix is `_exit(127)` after the message.

**Exercise 13.7 ★★.**

Write `xargs_lite n command [argument...]`, which reads words from its standard input and runs the command with its arguments followed by at most $n$ of the words at a time, until the words run out, and exits with the largest status it met. `printf 'a b c d e' | xargs_lite 2 echo X` prints `X a b`, `X c d`, `X e`.

**Solution of Exercise 13.7.**

```c
int main(int argc, char **argv)
{
    if (argc < 3 || atoi(argv[1]) < 1 || argc - 2 + atoi(argv[1]) > MAXWORDS)
        return 2;
    int n = atoi(argv[1]), fixed = argc - 2, worst = 0;
    char *cmd[MAXWORDS + 1], word[256];
    for (int k = 0; k < fixed; k++)
        cmd[k] = argv[k + 2];                     /* the command and its own arguments */
    int used = 0;
    for (;;) {
        int got = scanf("%255s", word) == 1;
        if (got)
            cmd[fixed + used++] = strdup(word);
        if (used > 0 && (used == n || !got)) {    /* a full batch, or the last one */
            cmd[fixed + used] = NULL;
            int s = run(cmd);
            worst = s > worst ? s : worst;
            for (int k = 0; k < used; k++)
                free(cmd[fixed + k]);
            used = 0;
        }
        if (!got)
            return worst;
    }
}
```

*Batches of at most $n$ words code/bachelor-2/13-processes-and-system-calls/exercises/xargs_lite.c*

The vector holds the fixed words, then the batch, then a null pointer. A batch is run when it is full or when the input ends with words left over; each word is copied with `strdup`, since `word` is reused. The test checks the batches of the statement and that the exit status is the largest one met. Unlike the real `xargs`, this one runs nothing when there are no words at all.

**Exercise 13.8 ★★.**

Prove [Proposition 13.6](#prop-b2-processes-and-system-calls-fork-count) by induction on $n$. How many [processes](#def-b2-processes-and-system-calls-process) print in `fork_tree.c` with $n$ [forks](#def-b2-processes-and-system-calls-fork), and how many of them have depth $d$?

**Solution of Exercise 13.8.**

Let $T(k)$ be the number of [processes](#def-b2-processes-and-system-calls-process) a single [process](#def-b2-processes-and-system-calls-process) has become, itself included, after executing $k$ remaining `fork` calls, every [process](#def-b2-processes-and-system-calls-process) created executing the calls that remain after the one that created it. $T(0) = 1$. For $k \ge 1$, the first call leaves two [processes](#def-b2-processes-and-system-calls-process), the caller and its [child](#def-b2-processes-and-system-calls-tree), each with $k - 1$ calls to execute and the same rule; they act independently, so $T(k) = 2\,T(k - 1)$. By induction, $T(n) = 2^n$. In `fork_tree.c` each [process](#def-b2-processes-and-system-calls-process) prints once: $2^n$ lines. A [process](#def-b2-processes-and-system-calls-process)’s name lists the indices of the [forks](#def-b2-processes-and-system-calls-fork) it came out of as the [child](#def-b2-processes-and-system-calls-tree), and every set of indices occurs exactly once (at [fork](#def-b2-processes-and-system-calls-fork) $i$, each [process](#def-b2-processes-and-system-calls-process) alive has one copy that adds $i$ and one that does not). The [processes](#def-b2-processes-and-system-calls-process) of depth $d$ are the sets of size $d$: $\binom{n}{d}$ of them.

**Exercise 13.9 ★★.**

Write a built-in `cd` that also understands `cd -`, “back to the previous directory”, and prints the directory it returns to. Why must the previous directory be stored in the shell, and when must it be updated?

**Solution of Exercise 13.9.**

```c
int cd_builtin(int argc, char **argv)
{
    static char previous[4096] = "";
    char here[4096];
    if (!getcwd(here, sizeof here))
        return 1;
    const char *dir = argc > 1 ? argv[1] : getenv("HOME");
    int back = dir && strcmp(dir, "-") == 0;
    if (back && previous[0] == '\0') {
        fprintf(stderr, "cd: no previous directory\n");
        return 1;
    }
    if (back)
        dir = previous;
    if (!dir || chdir(dir) != 0) {
        fprintf(stderr, "cd: %s: cannot go there\n", dir ? dir : "(no HOME)");
        return 1;
    }
    if (back)
        printf("%s\n", previous);                 /* as bash does */
    strcpy(previous, here);                       /* only after a successful change */
    return 0;
}
```

*`cd` with `cd -` code/bachelor-2/13-processes-and-system-calls/exercises/cd_dash.c*

The previous directory belongs to the shell’s state between commands, like its working directory itself: a [child](#def-b2-processes-and-system-calls-tree) would forget it when it ends. It must be updated only after a successful change, and to the directory the shell was in before, so that `cd /nowhere` followed by `cd -` does not go anywhere surprising, and two `cd -` in a row swap back and forth. The test checks both.

**Exercise 13.10 ★★★.**

Add `&&` and `||` to `minish`: in `a && b`, `b` runs only if `a` succeeded; in `a || b`, only if it failed; the operators chain from left to right with equal precedence, as in the usual shells. Write `run_list(argv, run)`, which takes the words of a line and a function running one command, and returns the status of the last command run. What does `false && x || true` run?

**Solution of Exercise 13.10.**

```c
int run_list(char **argv, int (*run)(char **))
{
    int status = 0;
    int skip = 0;                                 /* this command is not to be run */
    char **start = argv;
    for (char **w = argv;; w++) {
        int end = *w == NULL;
        int and = !end && strcmp(*w, "&&") == 0, or = !end && strcmp(*w, "||") == 0;
        if (!end && !and && !or)
            continue;
        *w = NULL;                                /* cut the command out of the line */
        if (!skip && start != w)
            status = run(start);
        if (end)
            return status;
        skip = and ? status != 0 : status == 0;   /* a && b: b only after a success */
        start = w + 1;
    }
}
```

*Running a list joined by `&&` and `||` code/bachelor-2/13-processes-and-system-calls/exercises/andor.c*

The loop walks the words; at each operator, or at the end, it cuts the command before it with a null pointer and runs it unless it is to be skipped. The status stays that of the last command actually run, and decides whether the next one runs: after `&&` only if it is 0, after `||` only if it is not. In `false && x || true`, `false` runs and fails, `x` is skipped, the status is still 1, and `true` runs: the line succeeds. In `minish`, the loop calls `run_list(argv, run)` instead of `run(argv)`, with the built-ins handled in a `run` that checks for them. The test drives `run_list` with a fake `run` that records what it was asked to run.

**Exercise 13.11 ★★★.**

`lines.c` prints $n$ numbered lines of 10 bytes, by `printf`, with `printf`’s buffer or without it. Count its `write` [system calls](#def-b2-processes-and-system-calls-syscall) for $n = 1000$ in both modes, explain the two counts, and predict them for $n = 10\,000$. What would a terminal change?

```
$ gcc -O2 -o lines lines.c
$ strace -qq -e trace=write -o b.txt ./lines 1000 > /dev/null; wc -l < b.txt
3
$ strace -qq -e trace=write -o u.txt ./lines 1000 unbuffered > /dev/null; wc -l < u.txt
1000
```

***Output 13.13.** Each `write` is one line of `strace`’s output.*

**Solution of Exercise 13.11.**

Through the buffer, the 1000 lines of 10 bytes, 10 000 bytes, leave in blocks of 4096 bytes, the buffer size the library chose for an output that is not a terminal: $4096 + 4096 + 1808$, three `write`s. Without the buffer, each `printf` makes its own `write`: 1000. For $n = 10\,000$: 100 000 bytes, so $\lceil 100\,000 / 4096 \rceil = 25$ writes, against 10 000. On a terminal the library flushes at every newline, so the buffered mode also makes one `write` per line: buffering pays when the output goes to a file or a pipe.

**Exercise 13.12 ★★★.**

Write `ptree`, a program that starts two children, the first with two children of its own, gives them names, and prints its own [process tree](#def-b2-processes-and-system-calls-tree) from `/proc`, indented, as `pstree` would, before stopping them all. On Linux, `/proc/<pid>/task/<pid>/children` lists the PIDs of a [process](#def-b2-processes-and-system-calls-process)’s children and `/proc/<pid>/comm` holds its name. Make the output the same on every run.

**Solution of Exercise 13.12.**

```c
static void show(pid_t pid, int depth)
{
    char path[64], name[32], kids[4096] = "";
    name_of(pid, name, sizeof name);
    printf("%*s%s\n", 2 * depth, "", name);
    snprintf(path, sizeof path, "/proc/%d/task/%d/children", (int)pid, (int)pid);
    FILE *f = fopen(path, "r");
    if (f) {
        if (!fgets(kids, sizeof kids, f)) kids[0] = '\0';
        fclose(f);
    }
    struct proc list[64];
    int n = 0;
    for (char *w = strtok(kids, " \n"); w && n < 64; w = strtok(NULL, " \n"))
        list[n++].pid = atoi(w);
    for (int k = 0; k < n; k++)
        name_of(list[k].pid, list[k].name, sizeof list[k].name);
    qsort(list, n, sizeof list[0], by_name);      /* the order of the file is not promised */
    for (int k = 0; k < n; k++)
        show(list[k].pid, depth + 1);
}
```

*Printing a tree from `/proc` code/bachelor-2/13-processes-and-system-calls/exercises/ptree.c*

```c
int main(void)
{
    int fd[2];
    if (pipe(fd) != 0 || setpgid(0, 0) != 0)      /* our own group, for the final kill */
        return 1;
    prctl(PR_SET_NAME, "ptree");
    spawn("child-b", fd[1], 0);
    spawn("child-a", fd[1], 2);
    char c;
    for (int k = 0; k < 4; k++)                   /* a, b and a's two children are ready */
        if (read(fd[0], &c, 1) != 1)
            return 1;
    show(getpid(), 0);
    signal(SIGTERM, SIG_IGN);                     /* the group signal must spare us */
    kill(0, SIGTERM);
    while (wait(NULL) > 0)
        ;
    return 0;
}
```

*A small tree, shown, then stopped code/bachelor-2/13-processes-and-system-calls/exercises/ptree.c*

Three things make the output the same on every run. The tree is complete before it is printed: each [process](#def-b2-processes-and-system-calls-process) writes a byte to a pipe once it and its children exist, and the [parent](#def-b2-processes-and-system-calls-tree) reads four bytes first. The children are sorted by name, since the order of the `children` file is not promised. And no PID is printed. To stop the tree, the program puts it in a [process](#def-b2-processes-and-system-calls-process) group of its own, ignores the signal itself, and sends `SIGTERM` to the group. The test checks the output: `ptree`, then `child-a` with two `grandchild`ren, then `child-b`, indented by depth.

## 13.7 Problem: Building the tiny shell

**Problem 13.1.**

Weekend problem — Building the tiny shell

The problem rebuilds `minish` step by step, then counts the [system calls](#def-b2-processes-and-system-calls-syscall) it makes to run one command.

**Part I — Parsing.**

1. What does `split` produce for a line made of two spaces, `echo` , three spaces, `two` , a tab, `word` and a newline? Where do the strings of the vector live?
2. Why must the vector end with a null pointer?
3. What happens to the line `echo $? $?` after `false` ? To `echo x$?` ?
4. `strtok` keeps its position in a hidden static variable. Why is that harmless in `minish` and not in a recursive function?
5. A line of 2000 characters is typed. What does `fgets` with a buffer of 1024 do, and what does the shell then run?
6. Give a command line that `minish` cuts differently from a real shell.

**Part II — Fork, exec, wait.**

7. In `run` , which lines run in the [parent](#def-b2-processes-and-system-calls-tree) , which in the [child](#def-b2-processes-and-system-calls-tree) , and which in both?
8. Why does the shell call `fflush` before forking? Describe the output of `minish` on a script without it.
9. What does the [child](#def-b2-processes-and-system-calls-tree) do if `execvp` succeeds? What does it do if it fails, and why `_exit` rather than `return` ?
10. Where does `execvp` look for `echo` ? What changes if the line is `/usr/bin/echo hi` ?
11. Why does the shell wait before printing the next prompt? What would a script’s output look like if it did not?
12. How many [processes](#def-b2-processes-and-system-calls-process) exist, at most, while `minish` runs the script of the hook?

**Part III — Statuses and built-ins.**

13. Explain the four statuses printed by `echo $?` in the hook’s script.
14. What status does `run` return for a command killed by signal 9? Why add 128?
15. What does `minish` return when its input ends? When it reads `exit` ? `exit 300` ?
16. Why is `exit` built in? Use [Proposition 13.12](#prop-b2-processes-and-system-calls-cd-builtin) to say why `cd` is.
17. `pwd` is not built into `minish` , yet it prints the directory `cd` chose. Why?
18. Name one command that could be built in or not, with the same result, and one that could not.

**Part IV — The system calls of one command.**

```
$ gcc -o minish minish.c minish_parse.c
$ echo 'echo hi' > one.txt
$ PATH=/usr/bin strace -f -c -S name -o summary.txt ./minish < one.txt > /dev/null
$ awk '$1 !~ /^(%|-)/ { printf "%5d %4s  %s\n", $4, NF == 6 ? $5 : "", $NF }' summary.txt
    2    2  access
    4    2  arch_prctl
    6       brk
    1       clone
   21       close
    2       execve
    1       futex
    2       getrandom
    3    3  ioctl
   29       mmap
    8       mprotect
    2       munmap
   22       newfstatat
   32   13  openat
    8       pread64
    2       prlimit64
    6       read
    2       rseq
    3       set_robust_list
    2       set_tid_address
    1       wait4
    3       write
  162   20  total
$ : > none.txt
$ PATH=/usr/bin strace -f -c -o empty.txt ./minish < none.txt > /dev/null
$ awk '$NF == "total" { print $4, "calls for an empty script" }' empty.txt
41 calls for an empty script
$ PATH=/usr/bin strace -f -c -o alone.txt echo hi > /dev/null
$ awk '$NF == "total" { print $4, "calls for echo run alone" }' alone.txt
115 calls for echo run alone
```

***Output 13.14.** The calls of `minish` running `echo hi`, counted by `strace -f -c`, with the calls that failed; then two baselines.*

19. How many [system calls](#def-b2-processes-and-system-calls-syscall) does running `echo hi` through `minish` add to the shell’s own 41? How many of them does `echo` make by itself?
20. Of the 6 calls left, the trace shows that 5 are made by the shell and 1 by the [child](#def-b2-processes-and-system-calls-tree) before its [exec](#def-b2-processes-and-system-calls-exec) . Find the shell’s 5 from the code of `run` and of the loop. Under which names do `fork` and `waitpid` appear in the table?
21. Why are there 2 `execve` calls? Why would there be more with a longer `PATH` ?
22. `echo` alone makes 115 calls to print 3 bytes. Most of them are `openat` , `mmap` , `newfstatat` , `close` . What is it doing before it can print?
23. Using [Output 13.3](#out-b2-processes-and-system-calls-cost) , estimate the time of these 162 calls, if each cost what `getppid` costs. Is that the time of the command?
24. State the system-call budget of one external command.

**Solution of Problem 13.1.**

**1.** Three words, `echo`, `two` and `word`, then a null pointer: the tab and the newline are separators like the spaces. The strings are inside `line` itself: `strtok` writes a zero byte over the separator after each word, and the vector points into the line.

**2.** `execvp` receives no count: it finds the end of the vector by the null pointer, which the new program then sees as `argv[argc]`.

**3.** After `false` the last status is 1: `echo 1 1`, which prints `1 1`. `x$?` is not the word `$?`, so it stays as it is.

**4.** `split` finishes a line before the next one is cut, and nothing else calls `strtok` in between. A recursive function that called `strtok` on another string in the middle of its own loop would lose its position; `strtok_r` keeps the position in a variable of the caller.

**5.** `fgets` reads the first 1023 characters, without a newline; the shell runs them as a command, and the next `fgets` reads the rest of the line as a second command.

**6.** `echo "two words"`: `minish` passes two words, `"two` and `words"`, quotes included; a real shell passes one word, `two words`, without the quotes. `echo *` is another: no file names are expanded.

**7.** The lines before `fork` run in the [parent](#def-b2-processes-and-system-calls-tree) only. The two tests of `r` run in both [processes](#def-b2-processes-and-system-calls-process). The `execvp`, the message and `_exit` run in the [child](#def-b2-processes-and-system-calls-tree) only; `waitpid` and the return of the status in the [parent](#def-b2-processes-and-system-calls-tree) only.

**8.** When the output is a file, `printf`’s buffer is flushed only when full or at exit. Without the `fflush`, the prompts and echoed lines would accumulate in the shell’s buffer while each command’s output went out at once: the script’s output would show all the commands’ outputs first and all the `minish$` lines at the end.

**9.** If `execvp` succeeds, the [child](#def-b2-processes-and-system-calls-tree) runs the command and never comes back to `minish`’s code. If it fails, it prints the message and ends with status 127. A `return` would bring it back into the loop of a second shell ([Exercise 13.6](#exo-b2-processes-and-system-calls-6)); `exit` would flush the copies of the [parent](#def-b2-processes-and-system-calls-tree)’s buffers and run its exit handlers, where `_exit` ends the [process](#def-b2-processes-and-system-calls-process) at once.

**10.** In each directory of `PATH`, in order, until an `execve` succeeds. A word containing a `/`, like `/usr/bin/echo`, is executed as given, with no search.

**11.** So that the command’s output comes before the next prompt, and so that `$?` has the command’s status. Without the wait, prompts and outputs would mix in an order that changes from run to run, `$?` would be meaningless, and every ended command would stay a [zombie](#def-b2-processes-and-system-calls-zombie).

**12.** Two: the shell and the one [child](#def-b2-processes-and-system-calls-tree) it waits for. The built-ins create none.

**13.** `true` gives 0 and `false` 1, their exit statuses; `no-such-command` gives 127, the status the [child](#def-b2-processes-and-system-calls-tree) chose when its [exec](#def-b2-processes-and-system-calls-exec) failed; `cd /no/such/place` gives 1, the built-in’s failure.

**14.** $128 + 9 = 137$. Programs exit with statuses from 0 to 255 but rarely above 127; adding 128 to a signal number keeps the two cases apart in one number, as the usual shells do.

**15.** At the end of input, the last status, after printing a newline. For `exit`, the last status; for `exit 3`, 3. For `exit 300`, `main` returns 300, and the [parent](#def-b2-processes-and-system-calls-tree) of `minish` sees the low 8 bits, 44, as in [Output 13.7](#out-b2-processes-and-system-calls-status).

**16.** `exit` must end the shell’s own [process](#def-b2-processes-and-system-calls-process); a [child](#def-b2-processes-and-system-calls-tree) that exits ends only itself. A `cd` run in a [child](#def-b2-processes-and-system-calls-tree) would change only the [child](#def-b2-processes-and-system-calls-tree)’s directory, by [Proposition 13.12](#prop-b2-processes-and-system-calls-cd-builtin).

**17.** The built-in `cd` changed the shell’s own working directory, and every [child](#def-b2-processes-and-system-calls-tree) gets a copy of it at the [fork](#def-b2-processes-and-system-calls-fork), which the [exec](#def-b2-processes-and-system-calls-exec) keeps. `pwd` prints the directory it inherited.

**18.** `echo` prints the same whether built in or run as `/usr/bin/echo`. `cd` could not be a program, nor `exit`.

**19.** $162 - 41 = 121$ calls; `echo` alone makes 115.

**20.** The shell reads the line (`read`), asks whether its input is a terminal (`isatty`, an `ioctl`), flushes the prompt and the echoed line (`write`), creates the [child](#def-b2-processes-and-system-calls-tree) and waits for it. `fork` appears as `clone`, the Linux call that the library’s `fork` uses, and `waitpid` as `wait4`. The [child](#def-b2-processes-and-system-calls-tree)’s one call before its [exec](#def-b2-processes-and-system-calls-exec) is `set_robust_list`, made by the library in every new [process](#def-b2-processes-and-system-calls-process).

**21.** One `execve` starts `minish` under `strace`, the other is the [child](#def-b2-processes-and-system-calls-tree)’s [exec](#def-b2-processes-and-system-calls-exec) of `/usr/bin/echo`. `execvp` tries the directories of `PATH` in turn, and each directory that does not hold the program costs one failed `execve`, counted in the errors column; with `PATH=/usr/bin` the first attempt succeeds.

**22.** `echo` is dynamically linked: before `main`, the loader opens the C library, maps it into memory (`mmap`), protects its parts (`mprotect`) and closes the file; then the program’s locale set-up looks for locale and message files, many of which do not exist, which is why 13 `openat` calls fail. Only one call, `write`, does the work.

**23.** $162 \times 71.5\ \text{ns} \approx 11.6\ \mu\text{s}$. That is not the time of the command: `execve`, `clone` and `mmap` cost far more than `getppid`, the first touches of new memory cost page faults, and the programs also spend time in [user mode](#def-b2-processes-and-system-calls-modes).

**24.** On this machine, running one external command from `minish` costs 121 [system calls](#def-b2-processes-and-system-calls-syscall): 5 in the shell (`read`, `ioctl`, `write`, `clone` for the [fork](#def-b2-processes-and-system-calls-fork) and `wait4` for the wait), 1 in the [child](#def-b2-processes-and-system-calls-tree) before its [exec](#def-b2-processes-and-system-calls-exec), and 115 in `echo`, of which a single `write` prints the text. Starting a program, not its work, dominates the system-call budget of a small command.
