Duplicating descriptors with dup()
What you'll learn: How to use the dup() system call to create a copy of a file descriptor that points to the same open file.
The Copy-Paste of File Handles
Imagine you have a specific key that opens a locker. If you take that key to a locksmith and make a duplicate, you now have two separate physical keys. However, they both open the exact same locker. If you put a book in the locker using Key A, you can see that same book when you open it with Key B.
In C, file descriptors work the same way. When you open a file, the operating system gives you an integer (a file descriptor) that represents your connection to that file. The dup() system call allows you to "clone" that integer.
How dup() Works
The dup() function takes an existing file descriptor and returns a new one. This new descriptor is the lowest numbered slot available in your process’s file table. Both the old and the new descriptors share the same "file offset." This means if you read 10 bytes using the first descriptor, the second descriptor will also be positioned 10 bytes into the file. They are tethered to the same underlying file description.
Seeing it in Action
Here is how you might duplicate a descriptor in practice:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
// 1. Open a file to get an initial descriptor (fd1)
int fd1 = open("example.txt", O_WRONLY | O_CREAT, 0644);
// 2. Duplicate it (fd2)
// fd2 is now a new number, but points to the same file as fd1
int fd2 = dup(fd1);
// 3. Both can write to the same file
write(fd1, "Hello ", 6);
write(fd2, "World!", 6);
// 4. Clean up
close(fd1);
close(fd2);
return 0;
}
In this example, fd1 might be 3 and fd2 might be 4. Even though the numbers are different, they act as aliases for the same stream. If you close fd1, you can still use fd2 to write to the file. The connection only fully breaks when all duplicates are closed.
Why Use It?
You might wonder why we need two handles for one file. The most common reason is I/O Redirection. By duplicating a file descriptor into a specific slot—like slot 1 (Standard Output)—you can trick a program into sending its regular "print" statements to a file instead of the screen.
Key takeaway
The dup() system call creates a new file descriptor that points to the same open file as an existing one, sharing the same read/write position.