2017-03-09 38 views
0

我正在尝试查找未通过perl运行的进程。它适用于使用以下代码的一些进程,但不适用于cgred服务。如何在perl中为unix命令指定参数

foreach $critproc (@critarray) 
    { 
    #system("/usr/bin/pgrep $critproc"); 
    $var1=`/usr/bin/pgrep $critproc`; 
    print "$var1"; 
    print "exit status: $?\n:$critproc\n"; 
    if ($? != 0) 
      { 
      $probs="$probs $critproc,"; 
      $proccrit=1; 
      } 
    } 

对于cgred我必须指定/usr/bin/pgrep -f cgred检查所有PID是否与它有关或无关。 但是,当我在上面的代码中指定-f时,即使它没有运行,它也会为所有进程提供退出状态0$?)。

你能告诉我如何将参数传递给Perl中的unix命令吗?

感谢

回答

4

什么$critproc?你认为-f在哪里给你带来问题?有人可能会想象你有某种逃避的问题,但如果$critproccgred,那么你就不应该这么想。

鉴于这些问题,我只想回答一般问题。


下避免了外壳,所以没有必要建立一个shell命令:

system("/usr/bin/pgrep", "-f", $critproc); 
die "Killed by signal ".($? & 0x7F) if $? & 0x7F; 
die "Exited with error ".($? >> 8) if ($? >> 8) > 1; 
my $found = !($? >> 8); 

如果你需要一个shell命令,你可以使用字符串:: ShellQuote的shell_quote来构建它。

use String::ShellQuote qw(shell_quote); 

my $shell_cmd = shell_quote("/usr/bin/pgrep", "-f", $critproc) . " >/dev/null"; 
system($shell_cmd); 
die "Killed by signal ".($? & 0x7F) if $? & 0x7F; 
die "Exited with error ".($? >> 8) if ($? >> 8) > 1; 
my $found = !($? >> 8); 

use String::ShellQuote qw(shell_quote); 

my $shell_cmd = shell_quote("/usr/bin/pgrep", "-f", $critproc); 
my $pid = `$shell_cmd`; 
die "Killed by signal ".($? & 0x7F) if $? & 0x7F; 
die "Exited with error ".($? >> 8) if ($? >> 8) > 1; 
my $found = !($? >> 8);