我在教育方面遇到了这个小代码的问题。我无法理解它是如何运作的。
#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重定向它使用该文件作为输入?
答案 0 :(得分:4)
dup
始终为您提供最低的可用文件描述符编号。
默认情况下,0
,1
和2
的所有流程都会有stdin
,stdout
和stderr
。您正在打开一个文件,您将获得文件描述符值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读取它。