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

I'm not sure the best way to work this out.

I have a program that runs continously and prints to standard out when events happen. I need to write a script that executes this program, and acts on the output.

Would the best way to do this be to fork a child off, and pipe data back to parent? Or would it be easier to redirect the output of the program to a file and read that file?

Replies are listed 'Best First'.
Re: Running and Monitoring program output
by borisz (Canon) on Feb 20, 2004 at 17:05 UTC
    #!/usr/bin/perl open (my $fh, '-|', 'your program with params' ) || die $!; while ( defined ( $_ = <$fh> )) { #work on a event }
    Boris
Re: Running and Monitoring program output
by jweed (Chaplain) on Feb 20, 2004 at 17:17 UTC
    Well, I think your best bet would be to use the forking open.

    Here's how you might do that (this is straight from Cookbook 16.10):
    use IO::Handle; if ($pid = open $child, "-|") { while (<$child>) { #look ma! I'm processing! } close $child; } else { die "Couldn't fork: $!" unless defined $pid; STDOUT->autoflush(1); #exec program that wrties to STDOUT exit; }



    Code is (almost) always untested.
    http://www.justicepoetic.net/
Re: Running and Monitoring program output
by pzbagel (Chaplain) on Feb 20, 2004 at 17:05 UTC

    For a process that you want to run 24/7 I would suggest you write to a file and have your Perl script read that file. If you don't want to waste the space on the filesystem, you can also write to a named pipe which the Perl script can then read from. This separates the two processes so that they can be handled independently from each other. Important when we are talking about a service that is supposed to run all the time. Finally, if this is something you would be kicking off on the command-line from time to time, you could always use pipes to redirect the output of one into the input of another.

    <cmd1> | <cmd2.pl>