为什么回显$? returns 值与预期不同?
Why echo $? returns different value than expected?
我知道echo $?
returns前一个进程的退出状态。
在我的程序中,如果我的程序以 0
的状态代码结束,我会得到 0
。但是当程序以状态码-1
结束时echo $?
显示255
。 Whosebug 上有类似的问题,但没有解释为什么会这样。加上其中一个答案通常表示高于 128
的值表示一些错误和负退出代码。例如,147
- 我们可以通过从 147 减去 128 得到真正的退出代码,128 - 147 = -19,所以退出代码是 -19。
在我的电脑中,我发现 256 作为那个数字。例如 255 - 256 = -1,这是我的程序返回的。
为什么在不同的系统上这些数字会有所不同 128、256 以及为什么它们不能打印原始负代码而不是将这些数字添加到原始退出状态代码。
由于历史原因,退出代码被解释为无符号的一字节值。 "Normal" 错误代码为正 (<127),而 "abnormal" 错误代码(例如,通过终止信号产生的错误代码)为负 (>=128)。
尝试在 sleep 10
命令上按 Ctrl-C。退出代码是 130.
127 是 "command not found".
的结果
确实不建议明确使用负错误代码。
有关详细信息,请查看 wait()
手册页 (man 2 wait
),尤其是 WFEXITED()
和朋友。
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the
child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should
only be employed if WIFEXITED returned true.
(强调)
我知道echo $?
returns前一个进程的退出状态。
在我的程序中,如果我的程序以 0
的状态代码结束,我会得到 0
。但是当程序以状态码-1
结束时echo $?
显示255
。 Whosebug 上有类似的问题,但没有解释为什么会这样。加上其中一个答案通常表示高于 128
的值表示一些错误和负退出代码。例如,147
- 我们可以通过从 147 减去 128 得到真正的退出代码,128 - 147 = -19,所以退出代码是 -19。
在我的电脑中,我发现 256 作为那个数字。例如 255 - 256 = -1,这是我的程序返回的。
为什么在不同的系统上这些数字会有所不同 128、256 以及为什么它们不能打印原始负代码而不是将这些数字添加到原始退出状态代码。
由于历史原因,退出代码被解释为无符号的一字节值。 "Normal" 错误代码为正 (<127),而 "abnormal" 错误代码(例如,通过终止信号产生的错误代码)为负 (>=128)。
尝试在 sleep 10
命令上按 Ctrl-C。退出代码是 130.
127 是 "command not found".
的结果确实不建议明确使用负错误代码。
有关详细信息,请查看 wait()
手册页 (man 2 wait
),尤其是 WFEXITED()
和朋友。
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should only be employed if WIFEXITED returned true.
(强调)