Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Capturing System Output

by Anonymous Monk
on Mar 04, 2003 at 16:02 UTC ( [id://240389]=perlquestion: print w/replies, xml ) Need Help??

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

Hi,
Can anyone tell me how I can capture system output when using the system() command?

I.e. I want to check if a process is running and do something if it isn't

This doesn't work because $runcheck just equals 0

sub checkRunning {
my $runcheck = system("ps -deaf | grep httpd | grep -v grep | wc -l");
if ($runcheck > 0) {
&writeLog('rsync process already running');
return '';
} else {
return 'Not Running';
}
}

I'd be happy to hear any ideas about this thanks!
Tom

Replies are listed 'Best First'.
Re: Capturing System Output
by BazB (Priest) on Mar 04, 2003 at 16:11 UTC

    Use backticks, not system if you want to capture the output.

    system runs a command and returns, exec run commands and never returns, backticks run the command and lets you capture the output.

    perldoc is your friend. See the entries for system, exec and the perlop page for backticks.


    If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
    That way everyone learns.

Re: Capturing System Output
by hardburn (Abbot) on Mar 04, 2003 at 16:17 UTC

    system() doesn't return the output, just the exit status. There are other ways of executing programs that will give you the exit status. For instance, use open() with a pipe:

    open(EXEC, '-|', 'ps', '-deaf | ', 'grep', 'httpd |', 'grep', '-v', 'grep |', 'wc', '-l') or die "Can't exec: $!\n"; # Now read the output just like a file while(my $line = <EXEC>) { chomp $line; print "$line\n"; } close(EXEC);

    Backticks and qx// also work:

    my $input = `ps -deaf | grep httpd | grep -v grep | wc -l`; my $input2 = qx/ps -deaf | grep httpd | grep -v grep | wc -l/; # Same +thing

    ----
    Reinvent a rounder wheel.

    Note: All code is untested, unless otherwise stated

Re: Capturing System Output
by ignatz (Vicar) on Mar 04, 2003 at 16:17 UTC
    #!/usr/local/bin/perl use strict; use warnings; my @foo = `ps -deaf | grep httpd | grep -v grep | wc -l`; foreach (@foo) { print; }
    ()-()
     \"/
      `
    
      Ah cool! cheers for that guys! ;-)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-25 18:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found