dup2() — Duplicate an open file descriptor to another

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
Single UNIX Specification, Version 3

both  

Format

#define _POSIX_SOURCE
#include <unistd.h>

int dup2(int fd1, int fd2);

General description

Returns a file descriptor with the value 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:
  • If fd2 is less than 0 or greater than OPEN_MAX, dup2() returns -1 and sets errno to EBADF.
  • If fd1 is a valid file descriptor and is equal to fd2, dup2() returns fd2 without closing it; F_CLOEXEC is not cleared.
  • If fd1 is not a valid file descriptor, dup2() fails and does not close fd2.
  • If a file descriptor does not already exist, dup2() can be used to create one, a duplicate of fd1. F_CLOEXEC is cleared in fd2.
Note: If fd1 is an XTI endpoint, fd2 must not exceed 65535.

Returned value

If successful, dup2() returns fd2.

If unsuccessful, dup2() returns -1 and sets errno to one of the following values:
Error Code
Description
EBADF
fd1 is not a valid file descriptor, or fd2 is less than 0 or greater than OPEN_MAX.
EINTR
dup2() was interrupted by a signal.

Example

CELEBD06
⁄* CELEBD06

   This example duplicates an open file descriptor, using dup2().

 *⁄

#define _POSIX_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sys⁄stat.h>
#include <sys⁄types.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#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