There are alot of documents and discussion around the file descriptors of shells and how those file descriptors can be manipulated for redirection etc.
My question is, when a shell command is an external program, like rsync, cat, curl etc, do those commands have file descriptors in the same way the shell does?
To give a concrete example, if I run this command at a terminal prompt

% cat << EOF | php
echo "hello". PHP_EOL;
echo "another line" . PHP_EOL;

I'm assuming the contents of this heredoc are being fed to STDIN, but of which process? the shell, or does cat have a file descriptor 0 and the contents of the heredoc are being fed to cat's fd0 directly?


Lets begin by saying that all I/O whether file based, interactive or any other way require unique file descriptors for each.

The standardization of interactive file descriptors is what allows redirection and piping.

The shell is an expert at standard I/O manipulations.

In your example, cat is called with its STDIN set to the shell's output representing your HEREDOC script (sent through a popen()), and with its STDOUT piped (with popen()) to php's STDIN. php's output not being redirected, point to the shell's initial STDOUT.

  • I see, so the shell momentarily switches its STDOUT from the terminal to STDIN for the cat process. then all the rest of the pipe stuff happens, then the shells points its 1 (STDOUT) back to the terminal. And also because processes cat and php are involving IO then they definitely must have file descriptors! – the_velour_fog May 21 '16 at 4:10
  • The process that calls exec, in this case the shell, does close and open the file descriptors so they correspond to what is needed in the child process. – Julie Pelletier May 21 '16 at 4:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.