Why is the exit code 255 instead of -1 in Perl?

后端 未结 3 1308
礼貌的吻别
礼貌的吻别 2020-12-03 22:21

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

3条回答
  •  春和景丽
    2020-12-03 23:16

    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.

提交回复
热议问题