为什么在 Perl 中退出代码是 255 而不是 -1? [英] Why is the exit code 255 instead of -1 in Perl?

查看:36
本文介绍了为什么在 Perl 中退出代码是 255 而不是 -1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我将 Perl 中的退出代码 $? 移八位时,我得到 255,而我希望它是 -1?

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 位编码信号编号和指示是否发生核心转储的位.对于信号,退出状态被视为零——像 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 774048SO 179565.

这篇关于为什么在 Perl 中退出代码是 255 而不是 -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆