2017-03-09 56 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);