【问题标题】:capture exit code from system command in perl在 perl 中从系统命令中捕获退出代码
【发布时间】:2020-06-24 00:56:41
【问题描述】:

当我们通过“系统”调用命令时,如何正确捕获退出代码?从下面的测试用例中,我始终捕获“-1”,对于 code1 的期望是“0”,对于 code2 的期望是“1”。

test1.pl

use feature qw(say);
use strict;

my $code = system("./test2.pl 0");
say "code1  = $code";
system("./test2.pl 0");
say "code1' = $?";

$code = system("./test2.pl 1");
say "code2  = $code";
system("./test2.pl 1");
say "code2' = $?";

test2.pl

use feature qw(say);

use strict;

say "arg = @ARGV[0]";
my $exit_code = @ARGV[0];
say "this is a dummy script which exit with $exit_code";
exit $exit_code;

输出:

% ./project_r/test.pl
code1 = -1
code1' = -1
code2 = -1
code2' = -1

【问题讨论】:

  • % ./project_r/test.pl code1 = -1 code1' = -1 code2 = -1 code2' = -1
  • 我在 csh 中运行 perl 脚本
  • Re "我在 csh 中运行 perl 脚本",无关紧要。 system 始终使用 /bin/sh(Windows 除外),或者当它可以解析命令本身时根本不使用 shell(就像你的情况一样)。

标签: perl


【解决方案1】:

根据system 的文档,-1 表示尝试执行命令时出现问题,并且错误消息在$! 中找到。

system(...);
die("Can't run test2: $!\n") if $? == -1;
die("test2 killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("test2 exited with error ".( $? >> 8 )."\n") if $? >> 8;
say("Child completed successfully.");

this is a dummy 的输出不足可以看出,您的程序从未运行过。

可能的罪魁祸首是:

  • 路径未引用现有文件。
  • 该文件不可执行。

缺少的 shebang (#!) 行可能会使文件无法执行,但我假设您只是为了简洁而从 sn-ps 中省略了 shebang 行(因为./project_r/test.pl 否则不会运行) .

我还假设您发布的文件 (test1.pl) 和您执行的文件 (test.pl) 的名称不同。

我的最佳猜测是test2.pltest.pl/test1.pl 位于同一目录中,这不是当前目录,而是当前目录名为project_r 的子目录。

修复:

use FindBin qw( $RealBin );

my $code = system("$RealBin/test2.pl", "0");

【讨论】:

  • 按照您的建议修复代码后,它正在工作。只是对于我期望它返回 1 但我得到 256 的情况。这有什么线索吗?
  • 查看system 的文档或我回答中的第一个代码sn-p。
【解决方案2】:

请注意,如果您要从 Perl 程序运行其他 Perl 程序,则需要使用相同的设置。否则,您可能会遇到与父 perl 的设置一起使用不同 perl 的情况:

你当前的 Perl 在$^X:

system $^X, 'test2.pl', '0';

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2013-09-14
    • 2013-03-23
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2012-05-14
    • 2012-01-05
    相关资源
    最近更新 更多