dup, dup2 - duplicate a descriptor
int dup2(fd1, fd2)
int fd1, fd2;
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 low-
est 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:
o It refers to the same object that the old descriptor referred to.
o It uses the same seek pointer as the old descriptor. (that is, both
file descriptors share one seek pointer).
o It has the same access mode (read, write or read/write) as the old
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
dup() and dup2() return a new descriptor on success. On failure, they
return -1 and set errno to indicate the error.
EBADF fd1 or fd2 is not a valid active descriptor.
EMFILE Too many descriptors are active.
accept(2), close(2V), fcntl(2V), getdtablesize(2), lseek(2V), open(2V),
pipe(2V), read(2V), socket(2), socketpair(2), write(2V)
21 January 1990 DUP(2V)