[Previous]
[Contents]
[Next]

dup2()

duplicate a file descriptor

Synopsis:

#include <unistd.h>
int dup2( int filedes , int filedes2 );

Description:

The dup2() function duplicates the file descriptor given by the argument filedes. The new file descriptor is identical to the original, in that:

The number of the new descriptor is filedes2. If a file already is opened with this descriptor, the file is closed before the duplication is attempted.

The call

    dup_filedes = dup2( filedes, filedes2 );

is equivalent to

    close( filedes2 );
    dup_filedes = fcntl( filedes , F_DUPFD, filedes2 );

Returns:

The value of filedes2, or -1 if an error occurs; errno is set to indicate the error.

Errors:

EBADF
The argument filedes is not a valid open file descriptor, or filedes2 is out of range.
EMFILE
The number of file descriptors would exceed OPEN_MAX.

Examples:

#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

void main()
  {
    int filedes , dup_filedes ;

    filedes = open( "file",
        O_WRONLY | O_CREAT | O_TRUNC,
        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
    if( filedes != -1 ) {
      dup_filedes = 4;
      if( dup2( filedes, dup_filedes ) != -1 ) {

        /* process file */

        close( dup_filedes );
      }
      close( filedes );
    }
  }

Classification:

POSIX 1003.1

Safety:
Interrupt handler No
Signal handler Yes, but modifies errno
Thread Yes

See also:

chsize(), close(), creat(), dup(), eof(), errno, exec... functions, fcntl(), filelength(), fileno(), fstat(), isatty(), lseek(), open(), read(), setmode(), sopen(), stat(), tell(), umask(), write()


[Previous]
[Contents]
[Next]