dup2 / dup - 为什么我需要复制文件描述符?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (226)

我想了解使用dup2dup

从手册页:

DESCRIPTION

dup and dup2 create a copy of the file descriptor oldfd.
After successful return of dup or dup2, the old and new descriptors may
be used interchangeably. They share locks, file position pointers and
flags; for example, if the file position is modified by using lseek on
one of the descriptors, the position is also changed for the other.

The two descriptors do not share the close-on-exec flag, however.

dup uses the lowest-numbered unused descriptor for the new descriptor.

dup2 makes newfd be the copy of oldfd, closing newfd first if necessary.  

RETURN VALUE

dup and dup2 return the new descriptor, or -1 if an error occurred 
(in which case, errno is set appropriately).  

为什么我需要这个系统调用?复制文件描述符有什么用处?

提问于
用户回答回答于

dup系统调用重复一个现有的文件描述符,返回一个指向同一个底层I / O对象的新文件描述符。

Dup允许shell执行像这样的命令:

ls existing-file non-existing-file > tmp1  2>&1

以下示例代码运行程序wc,并将标准输入连接到管道的读取端:

int p[2];
char *argv[2];
argv[0] = "wc";
argv[1] = 0;
pipe(p);
if(fork() == 0) {
    close(STDIN); //CHILD CLOSING stdin
    dup(p[STDIN]); // copies the fd of read end of pipe into its fd i.e 0 (STDIN)
    close(p[STDIN]);
    close(p[STDOUT]);
    exec("/bin/wc", argv);
} else {
    write(p[STDOUT], "hello world\n", 12);
    close(p[STDIN]);
    close(p[STDOUT]);
}
用户回答回答于

复制文件描述符的另一个原因是使用fdopenfclose关闭传递给它的文件描述符fdopen,就是说如果你不希望原始文件描述符被关闭,你必须首先复制dup

所属标签

可能回答问题的人

  • 应用案例分享

    1 粉丝490 提问5 回答
  • o o

    4 粉丝495 提问5 回答
  • 找虫虫

    5 粉丝0 提问4 回答
  • 学生

    8 粉丝476 提问3 回答

扫码关注云+社区

领取腾讯云代金券