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:
- The shell forks three independent subprocesses (with some interconnected stdins and stdouts): one to run
gg/hh
, another forsleep 5
, and a third for the othergg/hh
. - All three run (or try to run) simultaneously.
- The shell begins waiting for all three to exit (with
waitpid()
or something similar). - 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. - Five seconds later, the
sleep 5
process finishes and exits. - 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.