2016-03-06 358 views
2

我在网上搜索了这个话题,并且遇到了这个解释,但我无法理解它的背后。代码和解释如下..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.*/ 

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

回答

2

这样的代码的目标是更改引用当前打开的文件的文件描述符编号。 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)可能不是严格必要的。有两个文件描述符引用同一个文件可能没问题。但是,在很多情况下,这可能会导致不良或意外的行为。

+0

对。在Windows下,关闭描述符是严格要求的,因为用于处理重复的OS函数,并且关闭描述符可确保句柄也关闭并释放资源。 –

相关问题