Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 612
onqtam Avatar asked Apr 19 '16 18:04

onqtam


2 Answers

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.

like image 104
Basile Starynkevitch Avatar answered Nov 04 '22 08:11

Basile Starynkevitch


Yes, it can overflow just like any other int.

The standard describes int to be at least 16 bits wide. Returning anything which does not fit into an int is undefined behaviour.

What the environment, in which the C++ program runs, does with the value, is implementation defined and not described by the standard.

Three values are mentioned by the C++ standard: EXIT_SUCCESS, EXIT_FAILURE and 0. Both 0 and EXIT_SUCCESS indicate successful program execution, while the other defines failure. EXIT_SUCCES is not required to be zero.

Quoting the C++11 standard:

If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_- FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.225

The usual values supported varies by implementation to implementation, Windows uses full 32 bit integers as return values, and the full 32 bits can be obtained through various means. POSIX only specifies how the 8 low order bits can be obtained, and thus shells often truncate the values returned.

like image 33
Leandros Avatar answered Nov 04 '22 08:11

Leandros