tags:

views:

506

answers:

3

Why is it that when I shift the exit code, $?, in Perl by eight, I get 255 when I expect it to be -1?

A: 

Which way are you shifting it? Please provide a code example.

also:

perldoc -f system

gives a very easy to understand example of what to do with $?

Also, http://www.gnu.org/s/libc/manual/html_node/Exit-Status.html

Exit values should be between 0 and 255. Your shifting combined with how negative values are actually stored by the computer should give some insight.

Bob
I was shifting it right by 8 bits
syker
+5  A: 

The exit status returned by 'wait()' is a 16-bit value. Of those 16 bits, the high-order 8 bits come from the low-order 8 bits of the value returned by 'exit()' - or the value returned from main(). If the program dies naturally, the low-order 8 bits of the 16 are all zero. If the program dies because of signal, the low-order 8 bits encode the signal number and a bit indicating whether a core dump happened. With a signal, the exit status is treated as zero - programs like the shell tend to interpret the low-order bits non-zero as a failure.

+-----------------+
|  exit  | signal |
+-----------------+

Most machines actually store the 16-bit value in a 32-bit integer, and that is handled with unsigned arithmetic. The higher-order 8 bits of the 16 may be all 1 if the process exited with 'exit(-1)', but that will appear as 255 when shifted right by 8 bits.

If you really want to convert the value to a signed quantity, you would have to do some bit-twiddling based on the 16th bit.

$status >>= 8;
($status & 0x80) ? -(0x100 - ($status & 0xFF)) : $status;

See also SO 774048 and SO 179565.

Jonathan Leffler
+3  A: 
Greg Hewgill
Awesome answer!
syker