Perl - How to read from a named pipe (fifo)

Here's some code from a Perl program where I open up a named pipe (a FIFO file), then read data from that file until the end of time ... or at least until someone kills this program.

my $fifo_file = "/opt/devdaily/ftpapp/ftp.fifo";

my $fifo_fh;
open($fifo_fh, "+< $fifo_file") or die "The FIFO file \"$fifo_file\" is missing, and this program can't run without it.";

# just keep reading from the fifo and processing the events we read
while (<$fifo_fh>)
{
  &handle_fifo_record($_);
}

# should never really come down here ...
close $fifo_fh;
exit(0);

As you can see there's not too much to this. Just open the fifo file like a regular file, then just keep reading the data that is passed into the other end of the pipe.

In my case the data records look something like this:

field1 | field2 | field3 | field4 | field5

so all I have to do is process each one of these records, one at a time, inside my program.

If you thought it might be hard to read from a named pipe, I hope this demonstrates that it's not hard at all.

 

Post new comment

The content of this field is kept private and will not be shown publicly.