Redirecting and Duplicating Descriptors
Learn how to duplicate and redirect file descriptors using dup() and dup2() to control where a program’s input and output are sent.
Every input or output operation ultimately uses an integer descriptor managed by the operating system. In this lesson, we'll explore how file descriptors can be duplicated and redirected using the system calls dup() and dup2(). These operations allow a program to change where its input and output go at runtime, a mechanism that makes shell redirection and pipelines possible.
Why duplicate a file descriptor
Each process maintains a table of file descriptors. By default, 0 means standard input, 1 means standard output, and 2 means standard error. If we change what descriptor 1 refers to, then all output normally sent to the terminal can instead be written to a file. Duplicating descriptors allows us to:
Redirect program output to a file.
Restore previous descriptors.
Implement shell-style redirection (
>,<).Build pipelines between processes.
The dup() system call
The simplest duplication function is: