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



我在网上搜索了这个主题并遇到了这个解释,但我无法理解它背后的想法。代码和说明如下。.

#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.*/

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

此类代码的目标是更改引用当前打开的文件的文件描述符编号。 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。

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

最新更新