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?
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 exits). 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:
UNIX error codes are a byte big, so your value is chopped down to its remainder mod 256, namely 208.
The C standard only defines three return codes: 0, EXIT_SUCCESS and EXIT_FAILURE. (Normally, EXIT_SUCCESS is 0, but I don't think that is technically required.)
If the status return is 0 or EXIT_SUCCESS, then "an implementation-defined form of the status successful termination is returned [to the host environment]". If it's EXIT_FAILURE, then "unsuccessful termination" is returned.
Any other return code is implementation-defined. Your implementation defines that a status return of 2000 returns 208 to the host-environment. It's completely within it's rights to do so.