I have a simple program to test exit codes:
int main() {
return 2000;
}
In the terminal if I run the program then type:
echo $?
the terminal replies with 208
. What? Why would it do that?
While the return value of main
is an int
(generally 32 bits), only 8 bits of the exit code are communicated out to the rest of the operating system.
As Mystical pointed out, 2000 % 256 = 208
.
In Linux, a parent process retrieves the status of a child process via a call to wait
or waitpid
(usually after the child exit
s). That call provides a status value - encoded in this int
is the exit code of the child, along with several other fields, indicating if/how the child exited, etc. The exit code is extracted via the WEXITSTATUS
macro.
int status;
waitpid(childpid, &status, 0);
if (WIFEXITED(status))
printf("Child exited with code %d\n", WEXITSTATUS(status));
It's interesting to note that I don't really see this mentioned in any of the man
pages, though!
But it's very apparent if we take a look at the kernel:
In kernel/exit.c
, we see where the exit
system call is defined:
888 SYSCALL_DEFINE1(exit, int, error_code)
889 {
890 do_exit((error_code&0xff)<<8);
891 }
You can see right there, that the int
error code is truncated to eight bits, and stuffed into bits 15:8 of the code passed to do_exit
.
Related questions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With