Why does my Perl script return a zero return code when I explicitly call exit with a nonzero parameter?

I have a Perl script that calls another script. A perl script should distribute the script return code, but it seems to return a null value to its caller (Java application) desipte by explicitly calling exit $scriptReturnCode .

The code and output are as follows (I understand that <=> may / should be != , But what I have):

 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; } 

Exit from my 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. 
+7
perl return-value
source share
2 answers

You need to shift the return code from system() by 8 bits.

eg. $exit_value = $? >> 8; # In your script $? $ scriptReturnCode

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

system() starts the command and returns information about the status of the output (as a 16-bit value: the lower 7 bits is the signal from which the process died, if any), and the high 8 bits are the actual value of the output

A more detailed code check for code outputs might also look like this:

 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; } 

UPDATE: According to the excellent ysth reminder, exit codes are truncated to 8 (low) bits, so a return of 256 instead of the expected 1 ends at 0. Likewise, a return of 257 ends at 1.

+9
source share

If grab $? and the offset of its value is too much to remember, you can simplify this code using IPC :: System :: Simple , which increments system() and feedback signals with more error checking and diagnostics, for example:

 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; 
+1
source share

All Articles