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 a file open in read-only mode, 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.

Note: The same file may be open via multiple open(), fopen(), etc. calls simultaneously but Blunk’s file systems only allow files to be opened once at a time in write mode. All other concurrent opens of the same file must be in read-only mode. This adds the read-only requirement to Blunk’s implementation of dup2().

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 the file for descriptor fid is not open in read-only mode.

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");