Shell – cat < file.txt Who is the responsible of reading the file

catio-redirectionshell

cat < file.txt

Who is the responsible of reading the file ?

Is the shell reads the open and read the file then write its content to the standard input of the command ?

Best Answer

For the shell command cat <file.txt:

  1. The redirection operator < causes the shell to open file.txt for reading.
  2. The shell executes the cat command, with its standard input connected to file.txt.
  3. The cat command reads from its standard input (so file.txt) and copies the content to its standard output.

So the shell is the one opening the file, but the cat command is the one reading the data.

You can observe what is going on by listing the system calls performed by the shell and its subprocesses. On 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
…

(22702 is the parent shell process, 22703 is the child cat)

The shell command cat file.txt works differently.

  1. The shell executes the cat command, passing it one parameter, namely file.txt.
  2. The cat program opens file.txt for reading.
  3. The cat command reads from file.txt and copies the content to its standard output.
Related Question