Part 5 of 6 · 3 min read
Redirection
Redirection: the gap between fork and exec
In plain words: Level 0, page 6 showed that a program writes its normal output to file descriptor 1. A shell can send that output to a file with >, and the program never knows. The trick uses the gap between fork and exec.
The child does these steps before exec:
- Open the file, which returns a descriptor, say 3.
- Call
dup2(3, 1), which makes descriptor 1 refer to the same open file as descriptor 3. Whatever 1 pointed to before is closed. - Close descriptor 3, which is no longer needed.
- Call
exec. The new program starts with descriptor 1 already pointing at the file.
The call exec keeps the open descriptors (page 3), so the program writes to "the screen" with printf and the text goes to the file. The parent shell is untouched, because all of this happened in the child's copy of the descriptor table.
A test on the test machine:
mysh> echo saved > o1.txt
mysh> cat o1.txt
saved
Both lines worked, and cat o1.txt printed saved read from the file. The file was created with mode 0644, meaning the owner may read and write it and others may only read.
Input redirection with < works the same way: open the file, dup2(fd, 0), close, exec. Appending with >> only changes the flag from O_TRUNC to O_APPEND.
Common mistake
Doing the dup2 in the parent instead of the child redirects the shell's own output, and every later command then writes to the file.
Interview angle
Answer in your head first, then open it.
How does a shell run a command?
It forks, the child calls exec on the program, and the parent waits.
Why is cd a built-in?
It changes the working directory of the process that runs it, so a child process would not affect the shell.
How does ls > out.txt work?
The child opens the file, uses dup2 to put it on descriptor 1, then calls exec.
Why are fork and exec separate calls?
The code between them lets a child be set up before the program starts.
Check yourself:
1. What does dup2(fd, 1) do?
2. Why is it done before exec?
3. What flag changes > into >>?
Words you will meet
| Word | Meaning |
|---|---|
| Shell | A program that starts programs for a user |
| Built-in | A command the shell runs itself |
| Working directory | The folder from which a process resolves relative names |
| Redirection | Sending a stream to a file instead of the terminal |
dup2 |
Make one descriptor refer to the same open file as another |
| Exit status | The number a command leaves for the shell |
Quick notes
- A shell is a user-mode program that reads commands typed by a user (or stored in a script), starts the programs they name as new processes, and waits for them to finish.
- A built-in command is a command that the shell executes by itself, within its own process, instead of starting another program.