Checking if the other end of a fifo is open

Frank Sorenson frank at
Thu Apr 9 17:48:03 MDT 2009

Hash: SHA1

Dave Smith wrote:
> I'm writing a bash script that communicates with a daemon process using
> a fifo. I am trying to bulletproof the script to safeguard myself if the
> daemon process crashes before it starts writing to the fifo. UNIX
> hackers will know that opening a fifo for reading will block until the
> writing side has opened the fifo for writing (and vice versa). I open
> the fifo for reading like this in bash:
>  exec 4< $my_fifo
> However, doing this is dangerous because the "exec" call will block
> until the daemon process opens the fifo for writing. This is usually
> fine, but if the daemon process *crashes* before it opens the fifo for
> writing, my script will hang indefinitely.
> So my question is this: Is there a way to check if a fifo is already
> open for writing so I can safely open it for reading. Even better: Can I
> do some "exec" magic with a timeout, such that if the open blocks for
> more than a few seconds, I can bail out somehow?
> Here is one caveat: I need to open the fifo exactly *once* and read many
> times, so I can't just do multiple "read" commands on it (which opens
> and closes the fifo each time). I'd be happy to be proven wrong on this
> point. :)
> --Dave


How about opening the fifo read/write, which doesn't block:
# exec 4<> dave_fifo
# ls -alF /proc/$$/fd
lrwx------ 1 sorenson sorenson 64 2009-04-09 18:14 4 -> /tmp/dave_fifo|

Here's an example script:

exec 4<> /tmp/dave_fifo
(sleep 2 ; kill -SIGUSR1 $$ ; echo "I'm alive" >&4) &

# Wait for the flag to get raised, or give up after a while:
read -t 5 -u 4 line
if [ $? -eq 0 ] ; then
        echo "The child said: $line"
        echo "Timed out waiting for child"

- --
Frank Sorenson - KD7TZK
Linux Systems Engineer, DSS Engineering, UBS AG
frank at
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Fedora -


More information about the PLUG mailing list