3

我对这个用于教育目的的小代码有疑问。我无法理解它是如何工作的。

#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”的内容。我不明白为什么!“更多”和 STDIN(键盘或文件)之间的链接在哪里?

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

4

1 回答 1

4

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

默认情况下,所有进程都将具有012、和。您正在打开一个文件,您将获得一个文件描述符值。之后你就关闭了。现在调用之后将为您提供最低可用值作为 的重复文件描述符,因此您将获得.stdinstdoutstderr3stdindup3stdin3

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模式下执行,通过从标准输入读取它。

于 2013-02-01T18:21:57.190 回答