cat < file.txt 谁负责读取文件?

far*_*oft 3 shell io-redirection cat

cat < file.txt
Run Code Online (Sandbox Code Playgroud)

谁负责读取文件?

shell 是否读取打开并读取文件,然后将其内容写入命令的标准输入?

Gil*_*il' 6

对于 shell 命令cat <file.txt

  1. 重定向操作符<使外壳打开file.txt以供读取。
  2. shell 执行cat命令,其标准输入连接到file.txt.
  3. cat命令从其标准输入 (so file.txt)读取并将内容复制到其标准输出。

所以shell是打开文件的那个,而cat命令是读取数据的那个。

您可以通过列出 shell 及其子进程执行的系统调用来观察正在发生的事情。在 Linux 上:

$ strace -f sh -c 'cat <file.txt' >/dev/null
execve("/bin/sh", ["sh", "-c", "cat <file.txt"], [/* 76 vars */]) = 0
…
open("file.txt", O_RDONLY) = 3
…
dup2(3, 0)                              = 0
…
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fbc737539d0) = 22703
[pid 22702] wait4(-1,  <unfinished ...>
[pid 22703] execve("/bin/cat", ["cat"], [/* 76 vars */]) = 0
[pid 22703] read(0, "wibble"..., 32768) = 6
[pid 22703] write(1, "wibble"..., 6) = 6
[pid 22703] read(0, "", 32768)          = 0
[pid 22703] close(0)                    = 0
[pid 22703] close(1)                    = 0
[pid 22703] close(2)                    = 0
[pid 22703] exit_group(0)               = ?
<... wait4 resumed> [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 22703
--- SIGCHLD (Child exited) @ 0 (0) ---
rt_sigreturn(0x11)                      = 22703
…
Run Code Online (Sandbox Code Playgroud)

(22702 是父 shell 进程,22703 是子进程cat

shell 命令的cat file.txt工作方式不同。

  1. shell 执行cat命令,并传递给它一个参数,即file.txt.
  2. cat程序打开file.txt阅读。
  3. cat命令读取file.txt内容并将其复制到其标准输出。