Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Getting output from continuous program

by jake7176 (Novice)
on Oct 18, 2016 at 15:23 UTC ( [id://1174213]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1174213]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-26 05:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found