Checking if the other end of a fifo is open

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


-----BEGIN PGP SIGNED MESSAGE-----
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. :)
> 
> TIA
> 
> --Dave

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:
#!/bin/bash

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"
else
        echo "Timed out waiting for child"
fi


Frank
- --
Frank Sorenson - KD7TZK
Linux Systems Engineer, DSS Engineering, UBS AG
frank at tuxrocks.com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iEYEARECAAYFAkneiTIACgkQaI0dwg4A47wOtACfcDhefbmAfD0Q711Yn4s7u1c+
EnQAnjYTyE6SAxZoIIzV9q3bxj7k6m/W
=7ozx
-----END PGP SIGNATURE-----



More information about the PLUG mailing list