Linux/bash 中程序返回值的有效范围是多少?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8082953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the valid range for program return value in Linux/bash?
提问by ysap
I have a C program which returns an integer value. I was surprised to find out that when examining the return value from the shell prompt I get the value modulo 256.
我有一个 C 程序,它返回一个整数值。我惊讶地发现,在检查来自 shell 提示的返回值时,我得到了模 256 的值。
/* prog.c */
int main(...) { return 257; }
--
——
> ./prog.e
> echo $?
1
- Why don't I see the whole integer?
- Where is this behavior documented?
- How can I get the whole 32-bit value to the shell?
- 为什么我看不到整个整数?
- 这种行为记录在哪里?
- 如何将整个 32 位值传递给 shell?
采纳答案by Doug Moscrop
When a program exits, it can return to the parent process a small amount of information about the cause of termination, using the exit status. This is a value between 0 and 255 that the exiting process passes as an argument to exit.
当程序退出时,它可以使用退出状态向父进程返回少量有关终止原因的信息。这是一个 0 到 255 之间的值,退出进程将其作为参数传递给退出。
http://www.gnu.org/s/hello/manual/libc/Exit-Status.html
http://www.gnu.org/s/hello/manual/libc/Exit-Status.html
alternatively:
或者:
http://en.wikipedia.org/wiki/Exit_status
http://en.wikipedia.org/wiki/Exit_status
came from "posix return codes" and "c return codes" respective Google searches.
来自“posix 返回代码”和“c 返回代码”各自的 Google 搜索。
回答by NPE
The explanation is right at the top of man exit:
解释就在顶部man exit:
The exit() function causes normal process termination and the value of status & 0377 is returned to the parent (see wait(2)).
In other words, only the lowest 8 bits are propagated to the parent process.
换句话说,只有最低的 8 位被传播到父进程。
In this respect, returning the exit code from main()is no different to passing it to exit().
在这方面,返回退出代码 frommain()与将其传递给exit().
回答by Mat
The return status is explained (sort of) in the waitand related syscalls.
返回状态在wait和相关的系统调用中进行了解释(某种程度上)。
Basically:
基本上:
WEXITSTATUS(stat_val)
If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().
WEXITSTATUS(stat_val)
如果WIFEXITED(stat_val)的值不为零,则此宏计算子进程传递给 _exit() 或 exit() 的状态参数的低 8 位,或子进程的值从 main() 返回的进程。
So it's limited to 8 bits. You can't portably get more than that. (With Linux kernel 2.6.9 and above, waitid(2) can be used to obtain the full 32 bits.)
所以它被限制为 8 位。你不能轻而易举地得到更多。(Linux 内核 2.6.9 及以上版本,可以使用 waitid(2) 获取完整的 32 位。)

