dup2() — オープン・ファイル記述子を別のファイル記述子に 複写

標準

標準/拡張機能 C/C++ 依存項目

POSIX.1
Single UNIX Specification、バージョン 3

両方  

形式

#define _POSIX_SOURCE
#include <unistd.h>

int dup2(int fd1, int fd2);

機能説明

fd2 のファイル記述子を 戻します。fd2 は、fd1 と同じファイルを参照するように なり、以前に fd2 によって参照されたファイルはクローズされます。以下の条件が適用されます。
  • fd2 が 0 よりも小さいか、OPEN_MAX よりも大きい 場合、dup2() は -1 を戻し、errno に EBADF を設定します。
  • fd1 が有効なファイル記述子で fd2 と等しい場合、dup2() は、fd2 をクローズしないで戻します。F_CLOEXEC はクリアされません。
  • fd1 が有効なファイル記述子でない場合、dup2() は失敗 し、fd2 をクローズしません。
  • ファイル記述子がまだ存在していない場合、dup2() を使用 して、fd1 と重複するファイル記述子を 作成できます。F_CLOEXEC は fd2 でクリアされます。
注: fd1 が XTI エンドポイントの場合、fd2 は 65535 を超えてはなりません。

戻り値

dup2() は、正常終了時には fd2 を戻します。

正常に実行されなかった場合、dup2() は -1 を戻して、errno を次のいずれかの値に設定します。
エラー・コード
説明
EBADF
fd1 が有効なファイル記述子ではありません。または、fd2 が 0 より小さいか、OPEN_MAX より大きいです。
EINTR
dup2() がシグナルによって割り込まれました。

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);
  }
}
出力:
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.

関連情報