2010-04-21 18 views
7

我有一個Perl腳本調用另一個腳本。 Perl腳本應該傳播腳本的返回代碼,但似乎將其調用者(Java應用程序)返回爲零,以致明確地調用。當我使用非零參數顯式調用exit時,爲什麼我的Perl腳本會返回零返回碼?

代碼和輸出如下(我知道<=>可以/應該是!=但是這就是我):

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. 

回答

9

你需要將來自system()的返回碼由8位移位。

E.g. $exit_value = $? >> 8;#在你的腳本中$?爲$ scriptReturnCode

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

system()運行的命令,並返回退出狀況信息(作爲16位值:低7位是該處理從,如果有的話,死亡的信號和高8位是實際出口價值的核心轉儲

更擴展的代碼檢查以及可能看起來像這樣:

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.

+0

假設你的意思'shift'在' $ scriptReturnCode = $ scriptReturnCode >> 8;' – 2010-04-21 10:57:51

+0

是的 - 更新。 – DVK 2010-04-21 11:09:53

+2

理想情況下,明確添加退出代碼在8(低)位截斷,因此返回256而不是預期的1結束爲0.同樣,返回257結束爲1等。 – ysth 2010-04-21 14:40:40

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; 
相關問題