In Unix-like operating systems, dup (short for "duplicate") and dup2 system calls create a copy of a given file descriptor. This new descriptor actually does not behave like a copy, but like an alias of the old one.
C library POSIX definition
The dup and dup2 calls are standardized by the POSIX specification.[1]
The former allocates the first available descriptor, just like open() behaves; an alternative way to duplicate a file descriptor to an unspecified place is the fcntl system call with F_DUPFD command.
The latter places the copy into newfd. If newfd is open, it is closed first.
dup2 for input/output redirection
{{expand section|date=March 2012}}
Unix shells use dup2 for input/output redirection. Along with pipe(), it is a tool on which Unix pipes rely.
The following example uses pipe() and dup() in order to connect two separate processes (program1 and program2) using Unix pipes:
See also
File descriptor – how it works and other functions related to open