gpt4 book ai didi

c++ - 作业dup2函数

转载 作者:行者123 更新时间:2023-11-30 02:06:58 24 4
gpt4 key购买 nike

我有一个关于家庭作业的问题,代码如下:

dup2(fd,0);
dup2(fd,1);
dup2(fd,2);
if(fd>2)
close(fd);

它说,

"To see why the if test is needed, assume fd is 1 and draw a picture of what happens to the three descriptor entries and the corresponding file table entry with each call to dup2. Then assume fd is 3 and draw the same picture."

我想知道我是否可以在这方面得到一些帮助,因为我很迷茫。

任何人都可以给我一个关于此 Material 的快速教程,因为我很难在我的书和网上找到它。谢谢。

最佳答案

如果 fd 为 3,它将关闭原本分别指向 stdin、stdout、stderr 的 fds 0、1、2,并创建 fd 的 3 个拷贝:0、1、2 都指向相同的目的地fd 3。现在您不需要 3,所以您关闭它,因为您已经有 0、1、2 指向 3 指向的位置,并且您不打算再使用 3。

如果 fd 为 1,它将关闭原本分别指向 stdin 和 stderr 的 fds 0、2,并创建 fd 的 2 个拷贝:0、2 都指向与 fd 1 (stdout) 相同的目的地.现在你确实需要 1 指向标准输出,因为你的程序的其余部分计划使用 1 作为标准输出,所以在这种情况下你不要关闭 fd。

因此你需要 if 语句,因为在一种情况下你需要关闭一个你不打算使用的 fd,而在另一种情况下你不需要关闭你打算使用的 fd。

手册页:http://linux.die.net/man/2/dup2

关于c++ - 作业dup2函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8306668/

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