【问题标题】:how to specify arguments to unix command in perl如何在 perl 中为 unix 命令指定参数
【发布时间】:2017-07-30 05:27:30
【问题描述】:

我正在尝试查找未通过 perl 运行的进程。它适用于使用以下代码的某些进程,但不适用于 cgred 服务。

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 命令。

谢谢

【问题讨论】:

    标签: perl unix rhel


    【解决方案1】:

    $critproc 是什么?你说的-f 哪里有问题?有人可能会认为您有某种转义问题,但如果您似乎暗示$critproccgred,情况就不应该如此。

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


    以下避免了shell,因此无需构建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命令,可以使用String::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);
    

    【讨论】:

      猜你喜欢
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2011-06-28
      • 2019-10-15
      • 2011-01-03
      相关资源
      最近更新 更多