当我用非零参数显式调用exit时,为什么我的Perl脚本返回零返回码?

时间:2010-04-21 10:35:19

标签: perl return-value

我有一个调用另一个脚本的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.

2 个答案:

答案 0 :(得分:10)

您需要将返回码从system()调用8位。

E.g。 $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。

答案 1 :(得分: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;