Home

dup2

dup2 is a POSIX system call and C library function that creates a duplicate of an existing file descriptor oldfd and places it in the descriptor number newfd. If newfd is currently open, dup2 closes it before duplicating oldfd. If oldfd and newfd are the same, the call succeeds and simply returns newfd.

After successful completion, both descriptors refer to the same open file description; the file offset and

Return value and errors: On success, dup2 returns newfd. On error, it returns -1 and sets errno.

Usage and portability: dup2 is widely available on Unix-like systems and is often used to redirect standard

status
flags
are
shared,
meaning
reads
and
writes
observe
the
same
position
and
flags
such
as
O_APPEND
are
shared
by
both
descriptors.
The
close-on-exec
flag
is
inherited
by
the
new
descriptor.
Common
errors
include
EBADF
when
oldfd
is
not
a
valid
open
file
descriptor,
EINTR
if
the
call
is
interrupted
by
a
signal,
and
EINVAL
if
newfd
is
invalid
or
out
of
range.
input,
output,
or
error
streams
in
shells
and
daemon
programs
before
an
exec
call.
It
is
the
POSIX-compliant
variant
of
duplicating
descriptors;
on
Windows,
similar
functionality
exists
under
different
APIs.