“dup”功能,“更多”和重定向

时间:2013-02-01 18:20:50

标签: c unix stdin dup

我在教育方面遇到了这个小代码的问题。我无法理解它是如何运作的。

#include <stdio.h>
#include <fcntl.h>

#define FNAME "info.txt"
#define STDIN 0
int main(){

   int fd;
   fd = open(FNAME, O_RDONLY);

   close(STDIN); //entry 0 on FDT is now free
   dup(fd); //fd duplicate is now stored at entry 0 
   execlp("more","more",0); 
}

通过启动此程序,它会在终端上打印文件“info.txt”的内容。我不明白为什么! “more”和STDIN(键盘或文件)之间的链接在哪里?

为什么如果我在没有args的情况下使用更多而没有重定向文件,它只显示一个帮助屏幕但是whit重定向它使用该文件作为输入?

1 个答案:

答案 0 :(得分:4)

dup始终为您提供最低的可用文件描述符编号。

默认情况下,012的所有流程都会有stdinstdoutstderr。您正在打开一个文件,您将获得文件描述符值3。之后你关闭了stdin。现在调用dup之后将为3提供最低可用值作为重复文件描述符,因此您将stdin作为3的重复文件描述符。< / p>

int main()
{
   int fd, fd2;
   fd = open(FNAME, O_RDONLY); //This will be 3

   fd2 = dup(fd); //This will be 4 because 4 is the lowest available value
   close(STDIN); //entry 0 on FDT is now free
   dup(fd); //fd duplicate is now stored at entry 0 
   execlp("more","more",0); 
}

这就是显示文件内容的原因,more命令可以两种方式使用。

  • 更多文件名
  • 命令|更

在您的exec中,您没有为filename命令提供任何more作为命令行参数。所以它在pipe模式下执行,从stdin读取它。