繁体   English   中英

从 perl 中的系统命令捕获退出代码

[英]capture exit code from system command in perl

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

测试1.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' = $?";

测试2.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;

Output:

% ./project_r/test.pl
code1 = -1
code1' = -1
code2 = -1
code2' = -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.");

正如您所见,缺少 output of this is a dummy ,您的程序从未运行过。

可能的罪魁祸首是:

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

缺少 shebang ( #! ) 行可能会导致文件不可执行,但我假设您只是为了简洁而从片段中省略了 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");

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

您当前的 Perl 位于$^X中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM