假设我有一个名为 fstatcheck 的程序。它从命令行获取一个参数并将其视为文件描述符。它检查文件描述符指向的文件的统计信息。
例如:
$./fstatcheck 1
l = 1
type: other, read: yes
另一个例子:
$./fstatcheck 3 < foobar.txt
l = 3
Fstat error: Bad file descriptor
问题:
第二个例子中的 shell 在做什么? 我可以猜到它以 3 作为文件描述符并开始分析 stat,但是描述符 3 没有打开。但是 shell 如何处理重定向?
我假设 shell 执行以下算法:
if (fork() == 0) { // What does the shell do here? execve("fstatcheck", argv, envp); }
有什么方法可以创建一个文件描述符 3 并让它连接到一个打开的文件表,该文件表仅使用 shell 命令(而不是使用 C 代码)指向 foobar.txt 文件 stat?
最佳答案
让我们用 strace
找出答案:
$ strace sh -c 'cat < /dev/null'
[...]
open("/dev/null", O_RDONLY) = 3
fcntl(0, F_DUPFD, 10) = 10
close(0) = 0
fcntl(10, F_SETFD, FD_CLOEXEC) = 0
dup2(3, 0) = 0
close(3) = 0
[...]
execve("/bin/cat", ["cat"], [/* 28 vars */]) = 0
[...]
因此在您的代码中,相关部分将是:
if (fork() == 0) {
int fd = open(filename, O_RDONLY); // Open the file
close(0); // Close old stdin
dup2(fd, 0); // Copy fd as new stdin
close(fd); // Close the original fd
execve("fstatcheck", argv, envp); // Execute
}
至于再开一个fd,绝对是:
myprogram 3< file
这将打开 file
用于阅读该程序的 fd 3。 <
alone 是 0<
的同义词.
关于linux - 当我们使用 "<"重定向时,shell 做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357566/