I want to understand that how does shell executes piped commands ? e.g. cat | more. I am aware that for executing a normal command shell does a fork, execute it and then child returns. But how does shell internally handle the execution of piped commands ?
Considering for example cat | grep
, the shell first forks itself to start cat
, and then forks itself once more to start grep
.
Before calling one of the exec*
family of functions in the two newly created processes to start the two programs, the tricky part is setting up the pipe and redirecting the descriptors. The pipe(2)
system call is used in the shell process before forking to return a pair of descriptors which both children inherit - a reading end and a writing end.
The reading end will be closed in the first process (cat
), and stdout will be redirected to the writing end using the dup2(2)
system call. Similarly, the writing end in the second process (grep
) will be closed and stdin will be redirected to the reading end again using dup2(2)
.
This way both programs are unaware of a pipe because they just work with the standard input/output.
It sets up a pipe using the pipe
system call, forks two processes instead of one and attaches one end of the pipe to the first process' stdout and the other end to the second process' stdin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With