为什么我不能从主函数返回更大的值?
我试图从主函数返回一个更大的值,例如 1000,但是当我输入 echo $?
时,它显示 0。
如果我返回一个较小的值,例如 100,它会显示正确的值。
我的代码:
int main(void)
{
return 1000;
}
我们可以返回的值有限制吗?
I am trying to return a bigger value like 1000 from my main function, but when I type echo $?
it displays 0.
If I return a smaller value like 100 it displays the correct value.
My Code:
int main(void)
{
return 1000;
}
Is there any limitation on the values which we can return?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有两个相关的概念:C 退出状态和 bash 返回代码。它们都涵盖 0-255 的范围,但 bash 出于自身目的使用 126 以上的数字,因此从程序中返回这些数字会很混乱。
为了安全起见,将退出状态代码限制为 0-127,因为这是最可移植的,至少 http://docs.python.org/library/sys.html#sys.exit。
C 退出状态放入 bash $?执行后变量,但 bash 使用 127 来指示“未找到命令”,因此您可能希望避免这种情况。 Bash 参考页面。
Bash 还使用 128-255 表示信号 - 它们表示进程被信号杀死:
退出代码 = 128 + 信号号
。因此,您也许可以使用接近 255 的数字,因为信号数字不太可能达到那么高。除了这些常见的指导方针之外,还有许多尝试来定义不同数字的含义:http:// /tldp.org/LDP/abs/html/exitcodes.html。
因此,如果您想从程序中返回任意整数,最好将其打印到标准输出,并从 bash 脚本中使用
VALUE=$(program)
捕获它。There are two related concepts here: C exit status, and bash return code. 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.
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.
The C exit status is put into the bash $? variable after execution, but bash uses 127 to indicate 'command not found' so you may want to avoid that. Bash reference page.
Bash also uses 128-255 for signals - they indicate the process was killed with a signal:
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.Beyond those common guide-lines there are many attempts to define what different numbers should mean: 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.main
的返回值(即应用程序的退出状态)在 *NIX 上被限制在 [0, 255] 范围内。 1000 超出范围,操作系统可能将其视为 0。The return value of
main
(i.e. the exit status of the application) is limited to the range [0, 255] on *NIX. 1000 is out of range, and the OS treats it as 0, presumably.在 Unix 领域,
main
的返回值是有限的,因为exit
的范围仅限于 8 位字节。在 Windows 中,有一个值
STILL_ACTIVE
,值为 259,最好避免将其作为进程退出代码。除此之外,在 Windows 中,您可以返回 32 位代码,例如
HRESULT
,这通常是这样做的。In Unix-land the return value of
main
is limited becauseexit
there is limited to the range of an 8-bit byte.In Windows there is a single value,
STILL_ACTIVE
with value 259, that is best avoided as process exit code.Other than that, in Windows you can return a 32-bit code such as an
HRESULT
and that is commonly done.