Home > Mobile >  Order of printing errors when piping in bash
Order of printing errors when piping in bash

Time:03-03

So my question is, when you type for example this command in bash gg/hh | sleep 5 | gg/hh it prints

bash: gg/hh: No such file or directory
bash: gg/hh: No such file or directory

then it sleeps. How do you imitate this behavior in C. Because you need to waitpid(pid, &status, 0) to get the status of the command you executed in order to print out No such file or directory. So how do you get the status of the execve in the child process without waiting for sleep to finish.

CodePudding user response:

The order of execution goes something like this:

  1. The shell forks three independent subprocesses (with some interconnected stdins and stdouts): one to run gg/hh, another for sleep 5, and a third for the other gg/hh.
  2. All three run (or try to run) simultaneously.
  3. The shell begins waiting for all three to exit (with waitpid() or something similar).
  4. The two gg/hh processes fail, print their error messages (to stderr, so they go straight to the terminal), and exit. The parent shell process is not involved in printing these error message, so the fact that it's paused does not matter.
  5. Five seconds later, the sleep 5 process finishes and exits.
  6. The parent shell process finishes waiting for its subprocesses, and prompts for a new command.

Note that the wstatus that waitpid() sets is not related to the error message(s); it's an integer that indicates whether the process succeeded or not, and maybe something about what went wrong. It's used to set the special parameter $?, but is not printed.

  • Related