DUP(2V)

NAME
dup, dup2 - duplicate a descriptor

SYNOPSIS
int dup(fd)
int fd;

int dup2(fd1, fd2)
int fd1, fd2;

DESCRIPTION

dup() duplicates an existing object descriptor. The argument fd is a small non-negative integer index in the per-process descriptor table. The value must be less than the size of the table, which is returned by getdtablesize(2). The new descriptor returned by the call is the lowest numbered descriptor that is not currently in use by the process.

With dup2(), fd2 specifies the desired value of the new descriptor. If descriptor fd2 is already in use, it is first deallocated as if it were closed by close(2V).

The new descriptor has the following in common with the original:

•   It refers to the same object that the old descriptor referred to.

•   It uses the same seek pointer as the old descriptor. (that is, both file descriptors share one seek pointer).

•   It has the same access mode (read, write or read/write) as the old descriptor.

Thus if fd2 and fd1 are duplicate references to an open file, read(2V), write(2V), and lseek(2V) calls all move a single seek pointer into the file, and append mode, non-blocking I/O and asynchronous I/O options are shared between the references. If a separate seek pointer into the file is desired, a different object reference to the file must be obtained by issuing an additional open(2V) call. The close-on-exec flag on the new file descriptor is unset.

The new file descriptor is set to remain open across exec system calls (see fcntl(2V).

RETURN VALUES

dup() and dup2() return a new descriptor on success. On failure, they return -1 and set errno to indicate the error.

ERRORS

EBADF
    fd1 or fd2 is not a valid active descriptor.

EMFILE
    Too many descriptors are active.

SEE ALSO
accept(2), close(2V), fcntl(2V), getdtablesize(2), lseek(2V), open(2V), pipe(2V), read(2V), socket(2), socketpair(2), write(2V)