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

Hello, Perl Monks


I am in need of some advice and I hope you can provide it to me.
I am trying to run a command using backticks:


push @results, `/engine/monitor`;

What I want to do, is store the output from monitor. However, because monitor provides a continuous stream of output (updating every second) my program just hangs.
I know this is because backticks waits until the program has finished before continuing, but this won't ever finish. I have also tried using:

system('/engine/monitor');

But that just provides me the return code. Which isn't needed.

Any help would be wonderful, thank you

Replies are listed 'Best First'.
Re: Getting output from continuous program
by Corion (Patriarch) on Oct 18, 2016 at 15:32 UTC

    You can open the subprocess as a filehandle and then read from that filehandle. See open for the simplest case and IPC::Open2IPC::Run2 and IPC::Open3IPC::Run3 for the more complex cases.

    my $cmd = '/engine/monitor'; my $pid = open my $fh, '-|', $cmd or die "Couldn't launch [$cmd]: $!/$?"; for( 1..10) { print scalar <$fh>; }; close $fh; # kills the child when it next tries to write kill $pid;
Re: Getting output from continuous program
by Discipulus (Canon) on Oct 18, 2016 at 15:39 UTC
    Hello jake7176

    you must use open against a program to read from (pipe sign at the end) open my $cmd,"/path/to/prog|"

    If you read carefully the open page you'll find many examples.

    Also of interest is this section of perlipc

    Then you can read from it as for normal filehandles.

    There are many other and refined options like IPC::Open2 and IPC::Open3 but also IPC::Run and Capture::Tiny

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.