Part 6 of 6 · 3 min read
Exercises
Easy
Easy 1: Parse a line (20 minutes)
Write the array that strtok produces from grep -n main file.c, including the final NULL.
Done when: you list five entries: grep, -n, main, file.c, NULL.
Hint
NULL ends the array.
Easy 2: Built-in or not (20 minutes)
For each of cd, ls, exit, cat and export, say whether it must be a built-in and why.
Done when: cd, exit and export are built-ins because they change the shell's state, and ls and cat are programs.
Hint
Ask whether a child could do the job and leave the shell unchanged.
Easy 3: Name the descriptor (20 minutes)
A command is run as prog > out.txt 2> err.txt. Say which descriptors the shell must redirect and where each goes.
Done when: descriptor 1 to out.txt and descriptor 2 to err.txt.
Hint
Descriptor 2 is standard error.
Medium
Medium 1: Run the shell (30 minutes)
Type the three pieces into mysh.c, compile with -Wall -Wextra, and run echo hi, ls /nonexistent and nosuch. Record the exit numbers that your shell prints.
Done when: the shell prints hi, then [exit 2] for the missing path and [exit 127] for the missing command.
Hint
A failed execvp leaves the child to report the error.
Medium 2: Add input redirection (30 minutes)
Extend the shell so that < file after a command connects descriptor 0 to the file. Test with wc -l < /etc/passwd.
Done when: the line count matches wc -l /etc/passwd, and a missing input file prints an error without running the command.
Hint
open with O_RDONLY, dup2(fd, STDIN_FILENO).
Medium 3: Add a pwd built-in (30 minutes)
Add pwd as a built-in using getcwd. Then show that cd /tmp followed by pwd prints /tmp.
Done when: the built-in works and a sentence explains why an external pwd would also work here, though cd cannot be external.
Hint
getcwd(buf, sizeof buf) then puts(buf).
Hard
Hard 1: Append and error redirection (60 minutes)
Add >> for appending and 2> for standard error. Test by running a failing ls with 2> err.txt and reading the file.
Done when: the error message is in err.txt and not on the screen, and a second run with >> adds a line instead of replacing the file.
Hint
O_APPEND replaces O_TRUNC, and the second target is STDERR_FILENO.
Hard 2: Report signals (60 minutes)
Change the shell so that when a child is killed by a signal it prints killed by signal N. Test with a program that calls abort() and one that dereferences a null pointer.
Done when: you see 6 for the abort and 11 for the null pointer.
Hint
WIFSIGNALED(status) and WTERMSIG(status).
Hard 3: Time every command (60 minutes)
Make the shell print the elapsed time of each command using clock_gettime. Run sleep 1 and ls, and compare. Explain what the number includes.
Done when: about 1.00 seconds for sleep 1 and a few milliseconds for ls, and a note that it includes fork, exec and the program's run time.
Hint
Take the time before fork and after waitpid.