gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:26:24 25 4
gpt4 key购买 nike

我正在尝试了解 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).

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

如果我有文件描述符,为什么要复制它?

如果您能解释一下并给我一个需要 dup2/dup 的示例,我将不胜感激。

谢谢

最佳答案

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

Dup 允许 shell 执行如下命令:

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

2>&1 告诉 shell 给命令一个文件描述符 2,它是描述符 1 的副本。(即 stderr 和 stdout 指向同一个 fd)。
现在在 non-existing file 上调用 ls 的错误消息和 existing filels 的正确输出显示在 tmp1 文件中。

以下示例代码在连接标准输入的情况下运行程序 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]);
}

child 将读取端复制到文件描述符0上,关闭文件dep 中的脚本和 wc 中的 execs。当 wc 从其标准输入中读取时,它从管道。
这就是使用 dup 实现管道的方式,现在使用 dup 的一种用途是使用管道构建其他东西,这就是系统调用的美妙之处,您使用已经存在的工具构建一个又一个的东西,这些工具又是使用构建的别的东西等等..最后,系统调用是您在内核中获得的最基本的工具

干杯:)

关于c - dup2/dup - 为什么我需要复制文件描述符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11635219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com