Dup (system call)


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.

C library POSIX definition

The dup and dup2 calls are standardized by the POSIX specification.

int dup ;
int dup2 ;

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

s 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 using Unix pipes:

  1. include
  2. include
  3. include
/* function prototypes */
void die;
int main
void die