Sunday, 12 February 2017

Inter-process communication with named pipes

As system administrators we frequently use pipes while working on the command line. Before getting to named pipes I'd like to start by describing unnamed pipes.
An unnamed pipe is the pipe (|) symbol we use to serve the output of one command as the input of another command. In system admin talk we commonly refer the usage of pipes as "piping out the output of a command".
For example, if I need to get the number of files/directories in my current working directory I could type ls | wc -l.



Unnamed pipes are short lived as they exist only for the duration of the command execution.

When we use named pipes however, we actually create a file of type pipe with the mkfifo command.
For example mkfifo myfile.


When I ran the ls -l command to view information on my named pipe, you can see the letter "p" at the very start of the output denoting that it is a pipe file and the color code of the file is also different from that of a regular file. When I run ls -F command we can see a pipe (|) symbol after the file name again indicative that the file is a named pipe.

Now that we've created our named pipe lets use it.

If I need to get a list of processes spawned by the user sa, I could type ps -ef | egrep "sa\s+" and pipe it to wc -l to get a count of the number of processes.
Instead of using an unnamed pipe, let's redirect the output of ps -ef | egrep "sa\s+" to our named pipe.


From the output you can ascertain that we did not get our prompt back after we directed the output of the command to the named pipe.
That is because we have yet to use the pipe as input to another process. Once we do that we'll get our prompt back.
So let's use our named pipe as standard input to the wc -l command in another terminal window and see what happens.


As soon as we hit enter after serving our named pipe as stdin to the wc -l command, we got our prompt back on the previous terminal window where we had redirected the output of our ps command to the named pipe. So the pipe serves as the link between the two processes such that output from one command/process is considered as the input to the second command/process thereby establishing inter-process communication.
Since our named pipe is not a regular file it will not store the output of the ps command we redirected to it earlier and it's size will be zero. So if we do a cat of the pipe file nothing will be displayed on screen and we won't get our prompt back unless we hit ctrl+c.



This article was an introduction to inter-process communication using named pipes and intended to serve as some food for thought. We can do more interesting things with named pipes.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...