Using Named Pipes (FIFOs) with Bash
It's hard to write a bash script of much import without using a pipe or two. Named pipes, on the other hand, are much rarer.
Like un-named/anonymous pipes, named pipes provide a form of IPC (Inter-Process Communication). With anonymous pipes, there's one reader and one writer, but that's not required with named pipes—any number of readers and writers may use the pipe.
Named pipes are visible in the filesystem and can be read and written just as other files are:
$ ls -la /tmp/testpipe prw-r--r-- 1 mitch users 0 2009-03-25 12:06 /tmp/testpipe|
Why might you want to use a named pipe in a shell script? One situation might be when you've got a backup script that runs via cron, and after it's finished, you want to shut down your system. If you do the shutdown from the backup script, cron never sees the backup script finish, so it never sends out the e-mail containing the output from the backup job. You could do the shutdown via another cron job after the backup is "supposed" to finish, but then you run the risk of shutting down too early every now and then, or you have to make the delay much larger than it needs to be most of the time.
Using a named pipe, you can start the backup and the shutdown cron jobs at the same time and have the shutdown just wait till the backup writes to the named pipe. When the shutdown job reads something from the pipe, it then pauses for a few minutes so the cron e-mail can go out, and then it shuts down the system.
Of course, the previous example probably could be done fairly reliably by simply creating a regular file to signal when the backup has completed. A more complex example might be if you have a backup that wakes up every hour or so and reads a named pipe to see if it should run. You then could write something to the pipe each time you've made a lot of changes to the files you want to back up. You might even write the names of the files that you want backed up to the pipe so the backup doesn't have to check everything.
Named pipes are created via mkfifo or mknod:
$ mkfifo /tmp/testpipe $ mknod /tmp/testpipe p
The following shell script reads from a pipe. It first creates the pipe if it doesn't exist, then it reads in a loop till it sees "quit":
#!/bin/bash
pipe=/tmp/testpipe
trap "rm -f $pipe" EXIT
if [[ ! -p $pipe ]]; then
mkfifo $pipe
fi
while true
do
if read line <$pipe; then
if [[ "$line" == 'quit' ]]; then
break
fi
echo $line
fi
done
echo "Reader exiting"
The following shell script writes to the pipe created by the read script. First, it checks to make sure the pipe exists, then it writes to the pipe. If an argument is given to the script, it writes it to the pipe; otherwise, it writes "Hello from PID".
#!/bin/bash
pipe=/tmp/testpipe
if [[ ! -p $pipe ]]; then
echo "Reader not running"
exit 1
fi
if [[ "$1" ]]; then
echo "$1" >$pipe
else
echo "Hello from $$" >$pipe
fi
Running the scripts produces:
$ sh rpipe.sh & [3] 23842 $ sh wpipe.sh Hello from 23846 $ sh wpipe.sh Hello from 23847 $ sh wpipe.sh Hello from 23848 $ sh wpipe.sh quit Reader exiting
Note: initially I had the read command in the read script directly in the while loop of the read script, but the read command would usually return a non-zero status after two or three reads causing the loop to terminate.
while read line <$pipe
do
if [[ "$line" == 'quit' ]]; then
break
fi
echo $line
done
Mitch Frazier is an Associate Editor for Linux Journal.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- I once had a better way I
1 hour 40 min ago - Not only you I too assumed
1 hour 58 min ago - another very interesting
3 hours 51 min ago - Reply to comment | Linux Journal
5 hours 44 min ago - Reply to comment | Linux Journal
12 hours 38 min ago - Reply to comment | Linux Journal
12 hours 54 min ago - Favorite (and easily brute-forced) pw's
14 hours 46 min ago - Have you tried Boxen? It's a
20 hours 37 min ago - seo services in india
1 day 1 hour ago - For KDE install kio-mtp
1 day 1 hour ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
Problems with trap
You should explicitly exit from the trap command, otherwise the script will continue running past it. You should also catch a few other signals.
So: trap "rm -f $pipe" EXIT
Becomes: trap "rm -f $pipe; exit" INT TERM EXIT
Excellent article. Thank you!
Not really necessary in this case
The EXIT trap gets executed when the shell exits regardless of why it exits so trapping INT and TERM aren't really necessary in this case.
However, your point about "exit" is good: trapping a signal removes the default action that occurs when a signal occurs, so if the default action is to exit the program and you want that to happen in addition to executing your code, you need to include an exit statement in your code.
Mitch Frazier is an Associate Editor for Linux Journal.
multiple readers
Thanks, good post.
One point to note, is that if you have multiple readers reading from the same pipe, only one of the readers will receive the output.
named pipe
I find named pipes of most use in feeding programs with data from network connections. Just make sure the program does not try to rewind the file.
mkfifo input
programxyz -f input
nc -lvvp 20000 > input
and on same macine or another send data to port 20000.
wow
Excellent article!
It's a nice complement to the famous Linux Journal Hall of Famer
http://www.linuxjournal.com/article/2156
by Andy Vaught.
With respect to your initial reader's implementation
while read line <$pipe
it seems to be a valid piece (meaning the redirection is pertinent to the "read", now the while loop; where the pipe would have been opened once.)
Another observation concerns a slightly modified final reader code:
while true; do if read line <$pipe; then if [[ "$line" == 'quit' ]]; then break else echo oops # Should not be executed fi echo $line fi done"echo oops" should not be - I think - ever executed, since "read" opens the pipe, reads one line and breaks, then opens it again and blocks waiting for input; however a simple test shows that it does:
oops
line: Hello from 27952
line: Hello from 27953
oops
line: Hello from 27954
oops
line: Hello from 27955
I guess that's a "Steven's UNIX Network Programming" moment - need to finally open and read it :-)
correction
misplaced the "ops" :-)
correction to the above
while true do if read line <$pipe; then if [[ "$line" == 'quit' ]]; then break fi echo "line: $line" else echo oops # Should not be executed. fi donenow it seems to be correct.
Very useful
Thank you for this - I didn't even know these existed - I have always used files for IPC between shell scripts. I guess I'm still a shell noob at heart ;)