Este libro aún no está disponible en Español. Ediciones: English.
University Computer Science — Year 2 · Grado — Año 2
13Processes 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 $?
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. 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 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; the operating system lets several processes 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. 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 holds code, global data, a heap and a stack. Chapter 10: 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 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 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 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 just after the instruction.
The C library wraps each system call in a function of the same name: write(fd, buffer, n) asks the kernel to write 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.
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 */
}
$ 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) = ?
write and exit_group system calls 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 with its arguments and result: two writes, of 14 and 15 bytes, and exit_group, the call that ends the process, which has no result since it never returns.
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.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, getppid, which only reads a number the kernel keeps:
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();
$ 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
-O2.A system call 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).
13.2 Creating a process: fork
Remark 13.3 (What the kernel keeps for a process)
Book 2’s 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 (PID) is a positive integer unique among the processes alive at the same time; a number freed by a process that has ended may be given to a later one.
Definition 13.4 (Parent, child, process tree)
A process that creates another is its parent, and the created one its child. Since every process but the first is created by another, the processes form a process tree, rooted at the first process the kernel starts.
Definition 13.5 (Fork)
A fork creates a new process by duplicating the caller. The system call fork() makes a child whose memory is a copy of the parent’s, with the same open files and working directory, and both processes continue from the return of fork. It returns 0 in the child and the child’s PID in the parent, or in the parent, with no child, if it fails.
One call, two returns: the only way for the code to know which process it is running in is the value fork returned. The copy is real: a variable changed in the child keeps its old value in the parent.
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;
$ 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
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, makes the parent wait until the child has ended, which fixes the order of the two lines. Linux does not copy the memory at the moment of the fork: the two processes 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 followed at once by an exec copies almost nothing.
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.A process that calls fork several times, with its children doing the same, grows a tree. In fork_tree.c each process names itself p followed by the indices of the forks it came out of as the child, and the parent waits for each child, so that each subtree finishes before the next fork:
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;
}
$ 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
fork_tree.c: an edge goes from a parent to a child. The fork of index is made by every process alive at that moment, and doubles their number.Proposition 13.6 (Counting forks)
If a process executes successive fork calls, and every process created continues from the same point and executes the remaining calls, then processes exist at the end, counting the first.
The proof is Exercise 13.8. With the output has eight lines, and the depth of each process, the number of forks it came out of as the child, takes the value for of them.
13.3 Running a program: exec
A fork makes a copy of the same program. To run another one, a process replaces its own program.
Definition 13.7 (Exec, argument vector)
An exec replaces the program of the calling 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, 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 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.
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;
$ 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
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 replaces exec_demo itself by printf, so the line after it is never printed, and the exit status of the process is printf’s. The fflush at the top matters for the same reason: an 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 waits for a child with waitpid(pid, &status, 0), which blocks until that child has ended and returns its PID; wait(&status) does the same for any child. The integer status encodes how the child 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.
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)));
}
$ 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
Signals are the subject of Chapter 14; here it is enough that raise(SIGTERM) sends the 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 as the status , so that one number covers both cases.
Between its end and its parent’s wait, a child is in a peculiar state: its program, memory and files are gone, but the kernel must keep its status until the parent asks for it.
Definition 13.9 (Zombie, orphan)
A zombie is a process that has ended but whose parent has not yet waited for it: only its entry in the kernel’s process table remains, with its PID and its status. An orphan is a process whose parent has ended before it; the kernel gives it a new parent, the first process or a process that asked to adopt orphans, which waits for it when it ends.
On Linux the kernel shows each process as a directory /proc/<pid>, whose file status has a line State:, with Z for a zombie. zombie.c reads that letter for a child that has ended, before and after waiting for it, then makes an orphan: a middle process starts a grandchild and ends at once, and the grandchild watches its own parent change.
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));
$ 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
After the wait, /proc has no entry any more: the letter - is the program’s way of saying so. A long-running parent that never waits accumulates zombies, each holding a PID, and PIDs are a finite resource (Exercise 13.2).
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, instead of running a program in a child.
The shell’s main loop:
Method 13.11 (The shell’s loop)
Repeat until the input ends or the command is exit:
- print a prompt and read one line;
- cut it into words; an empty line is skipped;
- if the first word names a built-in command, run it in the shell itself;
- otherwise fork; in the child, exec the program the first word names with the words as its argument vector, and if the exec fails, report it and end the child with status 127;
- in the parent, wait for the child, and keep its status for the next
$?.
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.
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;
}
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);
}
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;
}
The _exit(127) after a failed exec is essential. Without it the child returns from run into the shell’s loop, and two shells read the same input from then on (Exercise 13.6). It is _exit, not exit, so that the child does not flush a copy of the parent’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]
cd. Some lines are left out.Why are cd and exit built in? exit must end the shell, not a child. For cd, the reason is a theorem about processes.
Proposition 13.12 (A child cannot move its parent)
A change of working directory made by a process after a fork has no effect on the working directory of its parent. 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’s state, which fork copies (Definition 13.5). chdir changes the working directory of the process that calls it only; the copy in the parent is a separate value, which no call of the child touches. If cd were a program, the shell would fork a child and the child, after its exec, would change its own directory and end, leaving the shell where it was. ∎
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");
$ gcc -std=c17 -O2 -Wall -Wextra -o cd_child cd_child.c -lm && ./cd_child
child: now in /
parent: still where it was: yes
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 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, others such as echo only for speed. Its heart is still the loop of Method 13.11. Processes are also the way servers isolate work: a web server that forks 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.
int main(void)
{
fork();
fork();
printf("hello\n");
return 0;
}
printf code/bachelor-2/13-processes-and-system-calls/listings/exo_count.cSolution
Solution of Exercise 13.1.
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_count exo_count.c -lm && ./exo_count
hello
hello
hello
hello
The first fork makes two processes; both execute the second, which makes four, and each of the four prints once. The tree: the original process has two children, made by the first and the second fork; its first child has one child of its own, made by the second fork; the two others have none.
Exercise 13.2 ★
This parent never waits. Explain the output, what remains of each child, and when it would disappear.
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;
}
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
/proc.Solution
Solution of Exercise 13.2.
Each child ends at once, but its parent never waits: the kernel keeps its entry in the process table, with its PID and its exit status, in case the parent asks. The program counts the three, all in state Z. They disappear when the parent waits for them or when the parent itself ends: they then become orphans, adopted by a process that waits for them at once. A server that forks a child per request and never waits would fill the process table with zombies, 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
Solution of Exercise 13.3.
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 */
}
argv + 1 is already an argument vector: 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, and nobody waits. How many processes are created by the loop? How many times is fork called in all? How many of the final processes have no children?
Solution
Solution of Exercise 13.4.
The process that runs iteration of the loop, counting from 0, executes the remaining calls; by Proposition 13.6, processes exist at the end, so the loop created . Each successful call creates exactly one process, so fork was called times. A process created at iteration makes one child at each of the iterations : it has none exactly when . There are processes alive just before the last iteration, so are created by it: half of the final processes have no children.
Exercise 13.5 ★★
In which order are the letters printed? Could another order appear on another run?
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;
}
Solution
Solution of Exercise 13.5.
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_order exo_order.c -lm && ./exo_order
ABCDEFG
ABCDEFG, on every run. Each letter is printed after the previous one, because of a fork or a wait: A comes before the first fork; B is printed by the child; C by the grandchild, created after B; D by the child after it has waited for the grandchild; E by the parent after waiting for the child; F by a second child created after E; G after waiting for it. Every say flushes, so no letter is left in a buffer that a fork would copy.
Exercise 13.6 ★★
This program runs three commands, but a failed exec is not followed by _exit. Explain every line of its output.
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;
}
_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
done too many.Solution
Solution of Exercise 13.6.
The parent prints running true, runs true in a child and waits. Then it announces the missing command; the child’s execvp fails, and the child 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 . It prints running true, runs true in a child of its own, prints done and ends. Only then does the parent’s wait return; the parent goes on with 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 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
Solution of Exercise 13.7.
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;
}
}
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 by induction on . How many processes print in fork_tree.c with forks, and how many of them have depth ?
Solution
Solution of Exercise 13.8.
Let be the number of processes a single process has become, itself included, after executing remaining fork calls, every process created executing the calls that remain after the one that created it. . For , the first call leaves two processes, the caller and its child, each with calls to execute and the same rule; they act independently, so . By induction, . In fork_tree.c each process prints once: lines. A process’s name lists the indices of the forks it came out of as the child, and every set of indices occurs exactly once (at fork , each process alive has one copy that adds and one that does not). The processes of depth are the sets of size : 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
Solution of Exercise 13.9.
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.cThe previous directory belongs to the shell’s state between commands, like its working directory itself: a child 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
Solution of Exercise 13.10.
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;
}
}
&& and || code/bachelor-2/13-processes-and-system-calls/exercises/andor.cThe 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 numbered lines of 10 bytes, by printf, with printf’s buffer or without it. Count its write system calls for in both modes, explain the two counts, and predict them for . 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
write is one line of strace’s output.Solution
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: , three writes. Without the buffer, each printf makes its own write: 1000. For : 100 000 bytes, so 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 from /proc, indented, as pstree would, before stopping them all. On Linux, /proc/<pid>/task/<pid>/children lists the PIDs of a process’s children and /proc/<pid>/comm holds its name. Make the output the same on every run.
Solution
Solution of Exercise 13.12.
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);
}
/proc code/bachelor-2/13-processes-and-system-calls/exercises/ptree.cint 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;
}
Three things make the output the same on every run. The tree is complete before it is printed: each process writes a byte to a pipe once it and its children exist, and the parent 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 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 grandchildren, 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 it makes to run one command.
Part I — Parsing.
- What does
splitproduce for a line made of two spaces,echo, three spaces,two, a tab,wordand a newline? Where do the strings of the vector live? - Why must the vector end with a null pointer?
- What happens to the line
echo $? $?afterfalse? Toecho x$?? strtokkeeps its position in a hidden static variable. Why is that harmless inminishand not in a recursive function?- A line of 2000 characters is typed. What does
fgetswith a buffer of 1024 do, and what does the shell then run? - Give a command line that
minishcuts differently from a real shell.
Part II — Fork, exec, wait.
- In
run, which lines run in the parent, which in the child, and which in both? - Why does the shell call
fflushbefore forking? Describe the output ofminishon a script without it. - What does the child do if
execvpsucceeds? What does it do if it fails, and why_exitrather thanreturn? - Where does
execvplook forecho? What changes if the line is/usr/bin/echo hi? - Why does the shell wait before printing the next prompt? What would a script’s output look like if it did not?
- How many processes exist, at most, while
minishruns the script of the hook?
Part III — Statuses and built-ins.
- Explain the four statuses printed by
echo $?in the hook’s script. - What status does
runreturn for a command killed by signal 9? Why add 128? - What does
minishreturn when its input ends? When it readsexit?exit 300? - Why is
exitbuilt in? Use Proposition 13.12 to say whycdis. pwdis not built intominish, yet it prints the directorycdchose. Why?- 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
minish running echo hi, counted by strace -f -c, with the calls that failed; then two baselines.- How many system calls does running
echo hithroughminishadd to the shell’s own 41? How many of them doesechomake by itself? - Of the 6 calls left, the trace shows that 5 are made by the shell and 1 by the child before its exec. Find the shell’s 5 from the code of
runand of the loop. Under which names doforkandwaitpidappear in the table? - Why are there 2
execvecalls? Why would there be more with a longerPATH? echoalone makes 115 calls to print 3 bytes. Most of them areopenat,mmap,newfstatat,close. What is it doing before it can print?- Using Output 13.3, estimate the time of these 162 calls, if each cost what
getppidcosts. Is that the time of the command? - State the system-call budget of one external command.
Solution
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 only. The two tests of r run in both processes. The execvp, the message and _exit run in the child only; waitpid and the return of the status in the parent 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 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); exit would flush the copies of the parent’s buffers and run its exit handlers, where _exit ends the 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.
12. Two: the shell and the one child 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 chose when its exec failed; cd /no/such/place gives 1, the built-in’s failure.
14. . 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 of minish sees the low 8 bits, 44, as in Output 13.7.
16. exit must end the shell’s own process; a child that exits ends only itself. A cd run in a child would change only the child’s directory, by Proposition 13.12.
17. The built-in cd changed the shell’s own working directory, and every child gets a copy of it at the fork, which the 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. 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 and waits for it. fork appears as clone, the Linux call that the library’s fork uses, and waitpid as wait4. The child’s one call before its exec is set_robust_list, made by the library in every new process.
21. One execve starts minish under strace, the other is the child’s 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. . 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.
24. On this machine, running one external command from minish costs 121 system calls: 5 in the shell (read, ioctl, write, clone for the fork and wait4 for the wait), 1 in the child before its 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.