簡體   English   中英

當我用非零參數顯式調用exit時,為什么我的Perl腳本返回零返回碼?

[英]Why does my Perl script return a zero return code when I explicitly call exit with a non-zero parameter?

我有一個調用另一個腳本的Perl腳本。 Perl腳本應該傳播腳本的返回代碼,但似乎返回零到其調用者(Java應用程序)desipte顯式調用exit $scriptReturnCode

代碼和輸出如下(我意識到<=>可能/應該是!=但這就是我所擁有的):

print "INFO: Calling ${scriptDirectory}/${script} ${args}"
$scriptReturnCode = system("${scriptDirectory}/${script} ${args}");

if ( $scriptReturnCode <=> 0 ) {
        print "ERROR: The script returned $scriptReturnCode\n";
        exit $scriptReturnCode;
} else {
        print "INFO: The script returned $scriptReturnCode.\n";
        exit 0;
}

我從Java獲得的輸出是:

20/04/2010 14:40:01 - INFO: Calling /path/to/script/script.ksh arg1 arg2 
20/04/2010 14:40:01 - Could not find installer files <= this is from the script.ksh    
20/04/2010 14:40:01 - ERROR: The script returned 256
20/04/2010 14:40:01 - Command Finished. Exit Code: 0 <= this is the Java app.

您需要將system()調用的返回碼移位8位。

例如$exit_value = $? >> 8; $exit_value = $? >> 8; #在你的腳本中$? 是$ scriptReturnCode

來自http://perldoc.perl.org/perlfaq8.html

system()運行命令並返回退出狀態信息(作為16位值:低7位是進程死亡的信號,如果有的話,高8位是實際的退出值

更加擴展的代碼檢查coredump也可能如下所示:

system();
if ($? == -1) {
    print "failed to execute: $!\n";
} elsif ($? & 127) {
    printf "child died - signal %d, %s coredump\n",
           ($? & 127), ($? & 128) ? 'with' : 'without';
} else {
    printf "child exited with value %d\n", $? >> 8;
}

更新:根據ysth的優秀提醒,退出代碼被截斷為8(低)位,因此返回256而不是預期的1最終為0.同樣,返回257最終為1。

如果捕獲$? 並且改變其值太難以記住,您可以通過使用IPC :: System :: Simple來簡化代碼,這可以通過更多的錯誤檢查和診斷來增強system()和反引號,例如:

use IPC::System::Simple qw(run EXIT_ANY);

my $command = "${scriptDirectory}/${script} ${args}";
print "INFO: Calling $command\n";

# runs command through a shell first; does not die on any exit value
run(EXIT_ANY, $command);
my $scriptReturnCode = $IPC::System::Simple::EXITVAL;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM