Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does shell execute piped commands?

Tags:

shell

unix

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 ?

like image 324
cppdev Avatar asked Feb 24 '11 07:02

cppdev


2 Answers

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.

like image 104
Blagovest Buyukliev Avatar answered Oct 22 '22 18:10

Blagovest Buyukliev


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.

like image 37
Fred Foo Avatar answered Oct 22 '22 19:10

Fred Foo