In Unix-like operating systems, dup 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.
The dup and dup2 calls are standardized by the POSIX specification.
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.
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: