问题描述
为什么当我将退出代码$?在Perl中移位8时,如果我期望它是-1,我得到255?
Why is it that when I shift the exit code, $?, in Perl by eight, I get 255 when I expect it to be -1?
推荐答案
"wait()"返回的退出状态为16位值.在这16位中,高8位来自'exit()'返回的值的低8位-或main()
返回的值.如果程序自然死亡,则16位的低8位全为零.如果程序因信号而死,则低8位编码信号编号,而1位指示是否发生内核转储.对于信号,退出状态被视为零-像Shell这样的程序倾向于将非零的低阶位解释为失败.
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 |
+-----------------+
大多数机器实际上将16位值存储在32位整数中,并且使用无符号算术来处理.如果进程以"exit(-1)"退出,则16位中的高8位可能全为1,但是当右移8位时,它将显示为255.
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.
如果您真的想将值转换为带符号的数量,则必须基于第16位进行一些位旋转.
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;
另请参见和 SO 179565 .
这篇关于为什么在Perl中使用退出代码255而不是-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!