Tiny Shell
You'll turn typed lines into fork, exec and wait, add pipes, redirection and Ctrl-C handling, and then live in the result for an hour.
About
A shell is the program that turns the line you type into fork, exec and wait, and writing one is the best way to see how Unix fits together. You'll start by running single commands, then add pipes, redirection and background jobs, and finish with a shell you can actually use for an hour of real work. Pipes are where everyone gets stuck, because a stray open file descriptor keeps the reader waiting forever, so close what you don't use. Do the Process Tree badge first if fork and exec are still new.
At a glance
- Per requirement
- 25 XP
- Completion bonus
- 150 XP
- Requirements
- 6
- Takes
- One weekend
- Skill level
- Intermediate (months of practice)
- Cost
- Free
- Supplies
- You need some
- Where
- At home
- Other people
- On your own
Requirements
-
1
Read a line, split it into words, fork, exec the command and wait. Use fgets and a hand-rolled tokenizer on spaces, then execvp in the child and waitpid in the parent. Print the prompt again after each command. Handle cd and exit yourself, because they can't be run as child processes. Take a screenshot of ls, cd and pwd working in your shell. Photo
-
2
Add output and input redirection with > and <. Open the file in the child before exec and dup2 it onto file descriptor 1 or 0. Make sure a bad filename prints an error rather than crashing the shell. Take a screenshot of ls > out.txt followed by cat < out.txt working. Photo
-
3
Add a single pipe so ls | wc -l works. Create the pipe before forking, fork twice, dup2 the right ends, and close every descriptor you aren't using in each process. If wc never prints, you've left the write end open somewhere. Take a screenshot of three different two-command pipelines working. Photo
-
4
Extend it to any number of pipes so a five-command pipeline works. Loop over the commands, keeping the read end of the previous pipe for the next child, and have the parent wait for all of them at the end. Try cat file | sort | uniq -c | sort -rn | head. Take a screenshot of it running. Photo
-
5
Make Ctrl-C kill the running command but not your shell. Install a handler for SIGINT in the shell with sigaction, and reset it to the default in the child before exec. Run sleep 100, press Ctrl-C, and show the prompt comes back. Film a short clip of this. Video
-
6
Add background jobs with & and use your shell for an hour of real work. Don't wait for a command that ends in &, and reap it later with waitpid and WNOHANG so it doesn't become a zombie. Then do an hour of your normal terminal work in your shell and note what you missed most, whether that's history, tab completion or globbing. Take a screenshot of your shell with a background job and your note. Photo