Tuesday, February 26, 2013

Linux: The ‘|’ symbol


Hi Readers,

As many of the Linux users or to be precise UNIX users use combination of UNIX commands on shell to get a desired output. This is done by using ‘|’ symbol called as ‘PIPE’, but I am quite sure that most of you won’t know about this symbol and what it actually is and how it works. So let me tell you all what it is and what it does when you write some command like below-

ls –lrt | tail -3

The pipe symbol is an inter-process communication mechanism in UNIX which is known as ‘PIPE’. This pipe works only for inter process communication between two or more child process having a common parent process and not when there are two different parent processes for two child process separately. The basic functioning of pipe is shown in below diagram-
 
You need to remember that pipes are unidirectional in nature and therefore if one side (or descriptor) is taken for writing it will be fixed and other side is used for reading. When two different processes communicate that is to say parent process writes to pipe and child process reads from pipe then the diagrammatic representation is as below-


In the similar way the two way communication can be achieved where child also writes and parent reads but to achieve this you need to use two pipes, here one will not work. So the above diagram can be modified as below-
Now you are aware of communication using pipe and therefore there are two question which comes forth-
1-      How these UNIX command work using pipes?
2-      Since pipes does not work for two different parent process criteria then how this command actually gets executed?

So the answer for the first question is that when we write command like ls –lrt | tail -3, two separate process are created as you all may know that each command is created as a process. Here the two processes are P1=> ls –lrt and P2=> tail -3. So what happens is that output from P1 is stored in pipe which is read by P2 and P2 uses it as an input to its command and displays the output. Not only these two processes are present when this command is executed but also parent process is available which is called as ‘shell’. Since shell is common parent process the pipe works properly in this scenario and this answers the second question. To explain you the overall process below diagram will help-


Now I am sure that this may clarify your concepts on pipe and if you still have any queries, you are most welcome to ask them. I hope to receive your comments.

Thanks
Nakul

No comments:

Post a Comment