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

Fur*_*ğlu 4 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 file referenced by pfd,
and closes the original file descriptor to clean up.*/
Run Code Online (Sandbox Code Playgroud)

F线是做什么的?为什么它至关重要?

Vau*_*ato 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.
Run Code Online (Sandbox Code Playgroud)

最后,文件描述符 1 现在引用pfd以前的同一个文件,并且pfd不再使用该文件描述符。该引用已有效地从文件描述符转移pfd到文件描述符 1。

在某些情况下,close(pfd)可能并不是绝对必要的。有两个引用同一文件的文件描述符可能没问题。然而,在许多情况下,这可能会导致不良或意外的行为。