Trevor Hickey Trevor Hickey - 6 months ago 15
Bash Question

Why is my shell only detecting return codes between 0 - 255?

Take the following C++ program:

#include <cstdlib>
int main(){exit(-1);}


When I run this program in either
zsh
,
bash
, or
sh
, I get the following results:

$ ./test
$ echo $?
255
$





If I run:

#include <cstdlib>
int main(){exit(256);}


it produces the following:

$ ./test
$ echo $?
0
$





Is it normal for a shell to interpret return codes between 0 - 255?

Is it possible to produce values outside of this range?

Answer

C++ allows you to return two values from main: EXIT_SUCCESS and EXIT_FAILURE. Returning EXIT_SUCCESS is the same as returning 0, which has the same effect as calling std::exit(0).

The return value is passed back to the operating system in an implementation-defined manner, and what the OS does with the value is also implementation-defined. Finally, the semantics of returning any other value from main are implementation-defined, too.

C++ has nothing more to say on this subject. You need to consult your platform's documentation.