Redirecting and Duplicating Descriptors
Explore how to manage file descriptors in C using dup and dup2 system calls. This lesson helps you understand redirecting standard input and output by duplicating descriptors, allowing you to implement shell-style redirection and pipelines effectively.
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. ...