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

dup()和close()系统调用之间的关系是什么?,c,operating-system,C,Operating System,我在网上搜索过这个话题,发现了这个解释,但我无法理解它背后的含义。代码和解释如下 #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 fil

我在网上搜索过这个话题,发现了这个解释,但我无法理解它背后的含义。代码和解释如下

#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.*/
#包括
...
int pfd;
...
关闭(1);
dup(pfd);
关闭(pfd);//**第F行**//
...
/*上面的例子关闭了电流的标准输出
处理、重新分配标准输出以转到pfd引用的文件,
并关闭原始文件描述符以进行清理*/

F行是做什么的?为什么它很重要?

这样的代码的目标是更改引用当前打开的文件的文件描述符编号
dup
允许您创建一个新的文件描述符编号,该编号引用与另一个文件描述符相同的打开文件。
dup
函数保证使用尽可能低的数字<代码>关闭使文件描述符可用。这种行为组合允许这种操作顺序:

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


在某些情况下,
close(pfd)
可能并非绝对必要。有两个引用同一个文件的文件描述符就可以了。但是,在许多情况下,这可能会导致不希望的或意外的行为。

对。在Windows下,关闭描述符是严格必需的,因为OS函数用于句柄复制,关闭描述符可确保句柄也被关闭并释放资源。