DUP(2) BSD DUP(2)
NAME
dup, dup2 - duplicate a descriptor
SYNOPSIS
newd = dup(oldd)
int newd, oldd;
dup2(oldd, newd)
int oldd, newd;
DESCRIPTION
dup duplicates an existing object descriptor. The argument oldd 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, newd, is the
lowest-numbered descriptor not currently in use by the process.
The object referenced by the descriptor does not distinguish between
references using oldd and newd in any way. Thus, if newd and oldd are
duplicate references to an open file, read(2), write(2) and lseek(2)
calls all move a single pointer into the file, and append mode, non-
blocking I/O, and asynchronous I/O options are shared between the
references. If a separate pointer into the file is desired, you must
obtain a different object reference to the file by issuing an additional
open(2) call. The close-on-exec flag on the new file descriptor is
unset.
In the second form of the call, the value of the newd desired is
specified. If this descriptor is already in use, the descriptor is
deallocated first, as if a close(2) call had been done first.
ERRORS
dup and dup2 fail if either of the following is true:
[EBADF] oldd or newd is not a valid active descriptor.
[EMFILE] Too many descriptors are active.
SEE ALSO
accept(2), open(2), close(2), fcntl(2), pipe(2), socket(2),
socketpair(2), getdtablesize(2)
DIAGNOSTICS
A successful call to either dup or dup2 returns 0. A failed call returns
-1 and sets errno to indicate the error.