Using named pipes via mkfifo
Oct 27, '04 10:10:00AM
Contributed by: fracai
Like inline pipes (|), named pipes allow output from one application to be sent to another. Named pipes, however, allow not just stdout redirection, but also redirection of any data output that would be written to disk. I was introduced to named pipes when I was converting a Real media file to MP3, and didn't want to save the uncompressed PCM audio in between conversion while using mplayer and lame.
First, a regular pipe, |, is pretty familiar and lets you do things like this:
$ touch blah
$ echo "blah" | cat > blah
Sure, that's overkill, but sending the output of one program to another can be very usefull.
Named pipes take it a step further by abstracting the concept of the pipe within the command line to a file representation. In my example of mplayer to lame, I would have to convert the Real media (30MB) to a raw PCM file (400MB) and then into MP3 with lame (30MB). The mplayer - lame combination doesn't support the inline pipe, but you can output PCM audio in real time by playing the Real media with mplayer, and lame will accept streaming PCM audio.
The process goes something like this:
- Create the pipe: mkfifo aNamedPipe
- Start lame with the pipe as input: lame -q 2 -b 128 aNamedPipe output.mp3
- start mplayer with the pipe as output: mplayer input.rm -ao pcm -aofile aNamedPipe
- Now just wait...
Named pipes are treated like regular files and can be removed with the rm command. The above example streams what would have been a very large file directly to the input of lame; While this example uses audio, named pipes are useful for many other tasks.
I'll end with the interesting exercise of what happens when multiple processes attempt to read the same pipe. Try the following with two terminal sessions, 1$ and 2$:
1$ mkfifo pipe
1$ cat > pipe
1$ tail -f pipe
2$ tail -f pipe
The following links contain additional information that is more detailed:
Comments (10)
Mac OS X Hints
http://hints.macworld.com/article.php?story=20041025103920992