Core · Module 5 · Lesson 6 of 12
Descriptor Duplication and Redirection with dup and dup2
Master file descriptor duplication, redirect standard streams atomically with dup2, and preserve I/O state across processes.
Pro — members onlyAbout 16 minutes
By the end you can
- Duplicate file descriptors to target identical Open File Descriptions using dup and dup2
- Implement standard stream redirection (stdout/stderr) for shell pipelines
- Explain the race condition eliminated by the atomicity guarantee of dup2
- Preserve and restore standard streams using temporary descriptor backups
Builds on Standard I/O Buffering vs System Calls.
01 · A question first
How does a Unix shell redirect program output to a file when you run `./app > out.txt`, even though ./app hardcodes calls to printf() targeting file descriptor 1? The answer lies in remapping process descriptor slots using dup2.
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Start with the problem
- How the idea works
- Why it is correct
- What it costs
- Pitfalls and variations
- Where it is used
03 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem