DUP(3) Library Functions Manual DUP(3)

dup dup2duplicate an open file descriptor

#include <unistd.h>

int dup(int fildes);
int dup2(int fildes, int fildes2);

The dup() and dup2() functions provide an alternative interface to the service provided by fcntl(3) using the F_DUPFD command. The call:

fid = dup(fildes);
is equivalent to:
fid = fcntl(fildes, F_DUPFD, 0);
The call:
fid = dup2(fildes, fildes2);
is equivalent to:
close(fildes2);
fid = fcntl(fildes, F_DUPFD, fildes2);
except for the following:
  • If fildes2 is less than 0 or greater than or equal to {OPEN_MAX}, dup2() returns -1 with errno set to [EBADF].
  • If fildes is a valid file descriptor and is equal to fildes2 , dup2() returns fildes2 without closing it.
  • If fildes is not a valid file descriptor, dup2() returns -1 and does not close fildes2 .
  • The value returned is equal to the value of fildes2 upon successful completion, or is -1 upon failure.

Upon successful completion a non-negative integer, namely the file descriptor, is returned. Otherwise, -1 is returned and errno is set to indicate the error.

The dup() function will fail if:

The fildes argument is not a valid open file descriptor.
The number of file descriptors in use by this process would exceed {OPEN_MAX}.

The function will fail if:

The fildes argument is not a valid open file descriptor or the argument fildes2 is negative or greater than or equal to {OPEN_MAX} .
The dup2() function was interrupted by a signal.

None.

None.

None.

close(3) , fcntl(3) , open(3) , <unistd.h> .

Derived from Issue 1 of the SVID.

February 1997 posix.fail