dup()和close()系统调用之间的关系是什么?

4
我在网上搜索了这个主题,看到了以下的代码和解释,但我无法理解其背后的思想。以下是代码和解释:
#include <unistd.h>
...
int pfd;
...
close(1);
dup(pfd);
close(pfd); //** LINE F **//
...

/*The example above closes standard output for the current
processes,re-assigns standard output to go to the file referenced by pfd,
and closes the original file descriptor to clean up.*/

LINE F是什么?为什么它至关重要?

1个回答

6

这段代码的目的是改变当前打开文件所引用的文件描述符号。 dup 允许您创建一个新的文件描述符号,该描述符号引用与另一个文件描述符号相同的打开文件。 dup 函数保证使用最低可能的数字。 close 使文件描述符号可用。 这种行为组合允许进行以下操作序列:

close(1);  // Make file descriptor 1 available.
dup(pfd);  // Make file descriptor 1 refer to the same file as pfd.
           // This assumes that file descriptor 0 is currently unavailable, so
           // it won't be used.  If file descriptor 0 was available, then
           // dup would have used 0 instead.
close(pfd); // Make file descriptor pfd available.

最终,文件描述符1现在引用了与"pfd"相同的文件,而"pfd"文件描述符未被使用。引用已从文件描述符"pfd"传递到文件描述符1。
在某些情况下,关闭"pfd"可能并不是必需的。拥有两个引用同一文件的文件描述符可能是可以的。然而,在许多情况下,这可能会导致不良或意外的行为。

正确。在Windows下,关闭描述符是必须的,因为使用了操作系统函数来进行句柄复制,关闭描述符可以确保句柄也被关闭并释放资源。 - Frankie_C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接