nzgrover has asked for the wisdom of the Perl Monks concerning the following question:

I need to:
Create a named pipe with a unique named.
Write a command to a (different) known named pipe.
Listen for the response on my unique named pipe.
Destroy the unique named pipe.

I have no problems creating and destroying the named pipe, however I've never done anything with named pipes before and though I've read up on their usage I'm not sure I'm reading/writing to them in a "safe" manner. In particular, I'm aware that if there is no corresponding writer/reader of the pipe then the write/read operation will block indefinitely. So when reading/writing to the pipe, i need to have a timeout. I thought the best way to do this would be to spawn a child process and make the parent kill the child if it took to long.
The "Reading" code.
my $result; my $named_pipe_name = '/path/to/pipe'; my $timeout = 5; #check to see if named pipe exists if (-p $named_pipe_name) { #fork in such a manner as to enable us to get out what the child # reads from the NP if (my $childpid = open(FROMCHILD, "-|")) { #parent #set up the a SIGCHLD handler that will read what the child has # written local $SIG{CHLD} = sub { $result .= <FROMCHILD>; }; #wait for our timeout sleep ($timeout); #kill the child (if it still exists) kill 'HUP', $childpid; } else { #child #Open for reading only. note using sysopen without create flag # to prevent creation of the named pipe as a normal file if (sysopen(FIFO, $named_pipe_name, O_RDONLY)) { my $return_string; #read from the name pipe till EOF while(my $this_line = <FIFO>) { chomp($this_line); $return_string .= $this_line; } close(FIFO); #tell the parent what we read print STDOUT $return_string; } else { print STDOUT "ERROR: Reading $named_pipe_name: $!"; } #exit causes the SIGCHLD to be sent. exit; } } print STDOUT $result;
The above works but I not confident it is the best way of doing this or even that it will be robust in the real world. Any enlightenment much appreciated!