Monday, March 4, 2013

Pipes and even more interesting Named Pipes

Pipes are very user friendly form of IPC on Linux. We are frequently using them in terminal, for example on Debian:

$ dpkg -l | grep gimp

We want to see only installed packages which are containing gimp in its name. Easy way to get pipe is to declare integer array and fork. Since child process gets all variables from parent it gets pipe as well.


Naturally such client server code is clumsy to write and creators of UNIX invented named pipes. Those are nothing but files and we can create them from terminal using mknod command and p switch, we want FIFO - first in first out storage:

$ mknod TESTFIFO p

Now if we do ls -l on our FIFO we will see that it got different color from other files and additional markings, letter p:

prw-r--r-- 1 borg borg 0 Mar  4 22:28 TESTFIFO

You do not have to be programmer to create FIFO. One can go even further and open two terminals, in the first execute cat > TESTFIFO and in the second one cat TESTFIFO, now everything what you write in the first one will appear in the second one, after you hit enter.
After all that fun we may go back to programming and create simple client and server which will use FIFO to talk. Client code:


Then server code:


Whoever starts first will be blocked until other side of pipe is open. When server exits, client exits as well. Very simple and user friendly.
Those examples are very much influenced by Linux Programmer's Guide by Scott Burkett and Beej's Guide to Unix IPC. The second one is quite entertaining and you can find it here with few other books and tutorials.
Next couple of posts will be about Java and pipes and Android and pipes and finally about NDK and pipes.

No comments:

Post a Comment