FAT | RFS | XFS | ZFS

dup2()

PROTOTYPE

#include <posix.h>

int dup2(int fid, int fid2);

DESCRIPTION

dup2() initializes fid2 as a duplicate descriptor referring to the same open file as fid. fid2 must be in the range [0, FOPEN_MAX-1]. If fid2 is invalid or fid is not the descriptor of an open file, dup2() returns -1. If fid2 equals fid, dup2() returns fid2. Otherwise, if fid2 already refers to an open file, that file is closed before its file control block is reused.

If successful, dup2() returns the value of fid2. That descriptor must be freed using close() when no longer needed. If an error occurs, it sets errno and returns -1.

ERROR CODES

EBADF fid2 is invalid or fid is not the descriptor of an open file.

EXAMPLE

  /*-------------------------------------------------------------------*/
  /* Open two files.                                                   */
  /*-------------------------------------------------------------------*/
  fid = open("file1.txt", O_RDWR);
  if (fid == -1)
    error("open() failed");
  fid2 = open("file2.txt", O_RDONLY);
  if (fid2 == -1)
    error("open() failed");

  /*-------------------------------------------------------------------*/
  /* Close second file and use its handle to refer to the first file.  */
  /*-------------------------------------------------------------------*/
  if (dup2(fid, fid2) != fid2)
    error("dup2() failed");