dup2

OS/161 Reference Manual

Name

dup2 - clone file handles

Library

Standard C Library (libc, -lc)

Synopsis

#include <unistd.h>

int
dup2(int oldfd, int newfd);

Description

dup2 clones the file handle oldfd onto the file handle newfd. If newfd names an already-open file, that file is closed.

The two handles refer to the same "open" of the file -- that is, they are references to the same object and share the same seek pointer. Note that this is different from opening the same file twice.

dup2 is most commonly used to relocate opened files onto STDIN_FILENO, STDOUT_FILENO, and/or STDERR_FILENO.

Both filehandles must be non-negative, and, if applicable, smaller than the maximum allowed file handle number.

The call (like all system calls) should be atomic; for single-threaded processes this is trivial. Multithreaded processes should never e.g. see an intermediate state where newfd has been closed but oldfd has not yet been cloned onto it. Similarly, if two threads attempt e.g. dup2(3, 4) and dup2(4, 3) simultaneously, the results must be equivalent to one of the calls completing before the other starts.

Using dup2 to clone a file handle onto itself has no effect.

(The "2" in "dup2" arises from the existence of an older and less powerful Unix system call "dup".)

Return Values

dup2 returns newfd. On error, -1 is returned, and errno is set according to the error encountered.

Errors

The following error codes should be returned under the conditions given. Other error codes may be returned for other cases not mentioned here.
  EBADF oldfd is not a valid file handle, or newfd is a value that cannot be a valid file handle.
EMFILE The process's file table was full, or a process-specific limit on open files was reached.
ENFILE The system's file table was full, if such a thing is possible, or a global limit on open files was reached.