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 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.

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 errors 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.