Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Capturing System Output

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

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

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!

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?

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2022-01-21 15:07 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (59 votes). Check out past polls.