In this lesson, you will learn how to dynamically redirect a process’s output by remapping its file descriptors (FDs) using low-level duplication techniques.
The Concept of Descriptor Duplication
A process tracks its open files via a File Descriptor Table. Every process starts with three standard streams: FD 0 (stdin), FD 1 (stdout), and FD 2 (stderr). Each entry in this table points to an "Open File Object" in the kernel.
"Duplication" involves copying an existing FD entry to a new slot in the table. When you duplicate an FD, the new descriptor points to the exact same file object as the original. This means they share the same file offset (the cursor position in the file). If you write data through the original FD, the offset updates for the duplicate as well.
Dynamic Remapping
Advanced users often need to swap where output goes while a program is already running. By duplicating an FD, you can effectively "hijack" a standard stream. For example, if you want a process to send its standard output to a log file instead of the terminal, you can:
- Open the log file (creating a new FD, e.g., 3).
- Duplicate FD 3 into the slot for FD 1 (stdout).
- The kernel now directs all "stdout" traffic into your log file.
Consider this logic in shell-level pseudo-code:
# Open log.txt for writing (gets FD 3)
exec 3>log.txt
# Duplicate FD 3 to FD 1 (replacing standard output)
# Now, any command that writes to stdout actually writes to log.txt
exec 1>&3
By performing this remapping, you gain control over the process environment without needing to restart the application. This is essential for background tasks or daemon processes that need to redirect their streams long after they have initialized. Because the kernel treats the duplicate and the original as identical references to the same file object, the process remains unaware that its underlying destination has been swapped.
Key Takeaway: Duplicating file descriptors allows you to point standard input/output streams to new destinations dynamically by cloning FD references within the process table.