问题
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.
/* 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?
回答1:
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.
http://www.gnu.org/s/hello/manual/libc/Exit-Status.html
alternatively:
http://en.wikipedia.org/wiki/Exit_status
came from "posix return codes" and "c return codes" respective Google searches.
回答2:
The explanation is right at the top of 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.
In this respect, returning the exit code from main()
is no different to passing it to exit()
.
回答3:
The return status is explained (sort of) in the wait and related syscalls.
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().
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.)
来源:https://stackoverflow.com/questions/8082953/what-is-the-valid-range-for-program-return-value-in-linux-bash