簡體   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