dup (system call)

In Unix-like operating systems, dup (short for "duplicate") and dup2 system calls create a copy of a given file descriptor.

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

When using the dup2() system call it performs the same task as dup() with the exception of using the file descriptor number specified in the newfd variable of the call, in that newfd is adjusted to refer to the oldfd file description.

The last system call in this family of functions is dup3(), which is the same as dup2() except that if oldfd equals newfd the system call fails with error EINVAL and the caller can force the close-on-exec flag to be set by specifying O_CLOEXEC in flags.

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.