[英]Why can't I return bigger values from main function?
I am trying to return a bigger value like 1000 from my main function, but when I type echo $?
我试图从我的主函数返回一个更大的值,比如 1000,但是当我输入
echo $?
it displays 0.它显示为 0。
If I return a smaller value like 100 it displays the correct value.如果我返回一个较小的值,如 100,它会显示正确的值。
My Code:我的代码:
int main(void)
{
return 1000;
}
Is there any limitation on the values which we can return?我们可以返回的值有什么限制吗?
There are two related concepts here: C exit status, and bash return code.这里有两个相关的概念:C 退出状态和 bash 返回码。 They both cover the range 0-255, but bash uses numbers above 126 for it's own purposes, so it would be confusing to return those from your program.
它们都涵盖 0-255 的范围,但是 bash 出于自己的目的使用 126 以上的数字,因此从您的程序中返回这些数字会令人困惑。
To be safe limit exit status codes to 0-127, as that is most portable, at least that is implied by http://docs.python.org/library/sys.html#sys.exit .为了安全起见,将退出状态代码限制为 0-127,因为这是最便携的,至少http://docs.python.org/library/sys.html#sys.exit暗示了这一点。
The C exit status is put into the bash $? C 退出状态放入 bash $? variable after execution, but bash uses 127 to indicate 'command not found' so you may want to avoid that.
执行后变量,但 bash 使用 127 表示“未找到命令”,因此您可能希望避免这种情况。 Bash reference page .
Bash 参考页。
Bash also uses 128-255 for signals - they indicate the process was killed with a signal: exit code = 128 + signal number
. Bash 还使用 128-255 作为信号 - 它们表示进程被信号杀死:
exit code = 128 + signal number
。 So you might be able to get away with using numbers close to 255 as it unlikely that signal numbers will go that high.因此,您可能可以使用接近 255 的数字,因为信号数字不太可能变得如此之高。
Beyond those common guide-lines there are many attempts to define what different numbers should mean: http://tldp.org/LDP/abs/html/exitcodes.html .除了这些通用指南之外,还有许多尝试定义不同数字的含义: http : //tldp.org/LDP/abs/html/exitcodes.html 。
So it you want to return an arbitrary integer from your program, it's probably best to print it to stdout, and capture it with VALUE=$(program)
from your bash script.所以如果你想从你的程序中返回一个任意整数,最好将它打印到标准输出,并从你的 bash 脚本中使用
VALUE=$(program)
捕获它。
The return value of main
(ie the exit status of the application) is limited to the range [0, 255] on *NIX. main
的返回值(即应用程序的退出状态)在 *NIX 上限制在 [0, 255] 范围内。 1000 is out of range, and the OS treats it as 0, presumably. 1000 超出范围,操作系统可能将其视为 0。
In Unix-land the return value of main
is limited because exit
there is limited to the range of an 8-bit byte.在 Unix-land 中,
main
的返回值是有限的,因为exit
被限制在 8 位字节的范围内。
In Windows there is a single value, STILL_ACTIVE
with value 259, that is best avoided as process exit code.在 Windows 中,有一个值为 259 的
STILL_ACTIVE
值,最好避免将其作为进程退出代码。
Other than that, in Windows you can return a 32-bit code such as an HRESULT
and that is commonly done.除此之外,在 Windows 中,您可以返回 32 位代码,例如
HRESULT
,这通常是这样做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.