Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Who prints what (20 minutes)
A program does pid = fork(); then prints "A" if pid == 0 and "B" otherwise. How many lines are printed and with which letters?
Done when: you write two lines, one "A" (child) and one "B" (parent), in either order.
Hint
The order of the lines depends on the scheduler.
Easy 2: Count the processes (20 minutes)
How many processes exist, counting the original, after fork(); fork(); fork(); fork();?
Done when: you write 16.
Hint
Double with each call.
Easy 3: When does exec return (20 minutes)
A program calls execvp("ls", args) and then prints "done". When is "done" printed?
Done when: you say it prints only if execvp failed.
Hint
A successful exec never returns.
Medium
Medium 1: Fork inside a condition (30 minutes)
Count the processes for fork(); if (fork()) fork();. Draw the tree.
Done when: you give 5 and a tree with each process labelled.
Hint
The inner fork() is true only in the parent.
Medium 2: Return the right code (30 minutes)
Write a program that forks a child that exits with 3. The parent must print "child exited with 3" using waitpid and WEXITSTATUS.
Done when: the program compiles with -Wall and prints the exact line.
Hint
waitpid(pid, &status, 0) and then the macro.
Medium 3: Run a command (30 minutes)
Write run.c that takes a command and its arguments from argv, forks, calls execvp in the child and waits in the parent. Print the exit status of the command.
Done when: ./run ls -l / and ./run false both work, and the second prints status 1.
Hint
execvp(argv[1], &argv[1]).
Hard
Hard 1: The duplicated output (60 minutes)
Run the ABC program with output to a terminal and again to a file. Explain every difference. Then add fflush(stdout) calls to make the file output match the terminal.
Done when: two outputs, an explanation with the buffer, and a fixed version.
Hint
A terminal is line buffered and a file is fully buffered.
Hard 2: A chain of children (60 minutes)
Write a program that creates a chain of 5 processes: each one forks one child, prints its PID and parent PID, and waits. Show that the last one's parent chain ends at the original process.
Done when: five lines with PID and PPID that form a chain, and no process left running.
Hint
Use recursion with a depth counter.
Hard 3: Signal or exit (60 minutes)
Write a parent that starts three children: one exits normally with 2, one calls abort(), one dereferences a null pointer. For each, print whether it exited or was killed and the number.
Done when: three lines such as "exited 2", "killed by signal 6" and "killed by signal 11".
Hint
Use WIFEXITED, WIFSIGNALED and WTERMSIG.