Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

dup, dup2 - duplicate file descriptor

&pagelevel(4)&pagelevel

Syntax

#include <unistd.h>

int dup(int fildes);

int dup2(int fildes, int fildes2); 

Description

fildes is a file descriptor obtained from a creat() , open(), dup(), fcntl, or pipe()
system call. dup() returns a new file descriptor having the following in common with the
original file descriptor:

  • the same open file or pipe

  • the same file position indicator

  • the same access mode (read, write or read/write)

fildes2 is a non-negative integer that is less than {OPEN-MAX}. dup2 causes fildes2 to point
to the same file as fildes. If fildes2 already points to an open file other than fildes, the open
file is first closed; however, if fildes2 points to fildes or if fildes is not a valid file descriptor,
fildes will not be first closed.

The dup() and dup2() functions provide an alternative interface to the service provided by
fcntl() 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 fildes is a valid file descriptor and is equal to fildes2, dup2() returns fildes2 without closing
it.

Return val.

Non-negative integer (the file descriptor)


if successful.

-1

if an error occurs; errno is set to indicate the error.

Errors

dup() and dup2() will fail if:

EBADF

fildes is not a valid open file descriptor or the argument fildes2 is negative
or greater than or equal to {OPEN_MAX}.

EINTR

Extension

EINVAL

EMFILE

dup2() was interrupted by a signal.

fildes and fildes2 designate BS2000 files. (End)

The number of file descriptors in use by the process would exceed
{OPEN_MAX}, or no fildes2 file descriptors are available.

Notes

See also

dup() and dup2() are executed only for POSIX files.

close(), fcntl(), open(), unistd.h.