Why is it that when I shift the exit code, $?, in Perl by eight, I get 255 when I expect it to be -1?
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.
15 8 7 0 Bit Position
+-----------------+
| 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.