gtpc2m1rC/C++ Language Support User's Guide

dup2-Duplicate an Open File Descriptor to Another

This function duplicates an open file descriptor to another.

Format

#include <unistd.h>
int dup2(int fd1, int fd2);

fd1
The open file descriptor to be duplicated.

fd2
The duplicate file descriptor.

This function returns a file descriptor with a value that is not less than fd2. fd2 now refers to the same file as fd1 and the file that was previously referred to by fd2 is closed. The following conditions apply:

Normal Return

If successful, the dup2 function returns fd2.

Error Return

If not successful, the dup2 function returns -1 and sets errno to the following:

EBADF
fd1 is not a valid file descriptor, or fd2 is less than 0 or greater than OPEN_MAX.

Programming Considerations

None.

Examples

The following example duplicates an open file descriptor using the dup2 function.

#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
 
void print_inode(int fd) {
  struct stat info;
  if (fstat(fd, &info) != 0)
    fprintf(stderr, "fstat() error for fd %d: %s\n", fd, strerror(errno));
  else
    printf("The inode of fd %d is %d\n", fd, (int) info.st_ino);
}
main() {
  int fd;
  char fn[]="DUP2.FILE";
  if ((fd = creat(fn, S_IWUSR)) < 0)
    perror("creat() error");
  else {
    print_inode(fd);
    if ((fd = dup2(0, fd)) < 0)
      perror("dup2() error");
    else {
      puts("After dup2()...");
      print_inode(0);
      print_inode(fd);
      puts("The file descriptors are different but they");
      puts("point to the same file which is different than");
      puts("the file that the second fd originally pointed to.");
      close(fd);
    }
    unlink(fn);
  }
}

Output

The inode of fd 3 is 3031
After dup2()...
The inode of fd 0 is 30
The inode of fd 3 is 30
The file descriptors are different but they
point to the same file which is different than
the file that the second fd originally pointed to.

Related Information

See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.