Search code examples
c++bashcmdterminalexit-code

Can the exit code of a process overflow for small values?


I am writing a testing framework and in main() I return the number of failed tests. For example:

int main() {
    int failedTests = runTests();
    return failedTests;
}

So can this "int" overflow? Can I get %ERROR_LEVEL% to be == 0 when I actually returned something different than 0? Does it depend on the host operating system? What are the usual maximum values? Can I be sure that an integer < 32768 (2^16 - a short) will always fit?

EDIT:

I've had problems with python sys.exit which uses the 0-127 range (almost) always so I am careful now


Solution

  • It depends upon the operating system. On Linux, it is restricted to 8 bits, so can be 0 (for success) or any positive integer not greater than 255. See _exit(2) & wait(2).

    Only two values are standardized (by name): EXIT_SUCCESS (usually it is 0) and EXIT_FAILURE (often as 1). Notice that the standard defines the name (and probably also the behavior of exit(0);...) but not their value.

    You could write the number (of failed tests) to stdout or to some file specified thru some program argument.

    FreeBSD has defined in its sysexits(3) a set of exit names and codes, but they are not standardized, e.g. in POSIX. See POSIX documentation on exit.