简体   繁体   English

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

[英]capture exit code from system command in perl

how can we capture the exit code correctly when we call a command via 'system'?当我们通过“系统”调用命令时,如何正确捕获退出代码? from the testcase below i consistently capture "-1" which the expectation is "0" for code1 and "1" for code2.从下面的测试用例中,我始终捕获“-1”,对于 code1 的期望是“0”,对于 code2 的期望是“1”。

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

test2.pl测试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: Output:

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

As per the documentation for system , -1 indicates there was a problem trying to execute the command, and that the error message is found in $!根据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.");

As you can see by the lack of output of this is a dummy , your program never ran.正如您所见,缺少 output of this is a dummy ,您的程序从未运行过。

Likely culprits are:可能的罪魁祸首是:

  • The path doesn't refer to an existing file.该路径不引用现有文件。
  • The file isn't executable.该文件不可执行。

A missing shebang ( #! ) line could render a file non-executable, but I'm presuming you simply left out the shebang lines from your snippets for conciseness (since ./project_r/test.pl wouldn't run otherwise).缺少 shebang ( #! ) 行可能会导致文件不可执行,但我假设您只是为了简洁而从片段中省略了 shebang 行(因为./project_r/test.pl否则不会运行)。

I'm also assuming that the difference in the name of the file you posted ( test1.pl ) and the file you executed ( test.pl ) isn't relevant.我还假设您发布的文件( test1.pl )和您执行的文件( test.pl )的名称不同是不相关的。

My best guess is that test2.pl is in the same directory as test.pl / test1.pl , which isn't the current directory but a subdircetory of the current directory named project_r .我最好的猜测是test2.pltest.pl / test1.pl位于同一目录中,这不是当前目录,而是当前目录名为project_r的子目录。

Fix:使固定:

use FindBin qw( $RealBin );

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

Note that if you are going to run other Perl programs from a Perl program, you need to use the same settings.请注意,如果要从 Perl 程序运行其他 Perl 程序,则需要使用相同的设置。 Otherwise you might run into situations where you are using a different perl with your parent perl 's settings:否则,您可能会遇到将不同perl与父perl的设置一起使用的情况:

Your current Perl is in $^X :您当前的 Perl 位于$^X中:

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

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

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