Why can't I return bigger values from main fun

2020-02-26 03:56发布

问题:

I am trying to return a bigger value like 1000 from my main function, but when I type echo $? it displays 0.

If I return a smaller value like 100 it displays the correct value.

My Code:

int main(void)
{
     return 1000;
}

Is there any limitation on the values which we can return?

回答1:

There are two related concepts here: C exit status, and bash return code. They both cover the range 0-255, but bash uses numbers above 126 for it's own purposes, so it would be confusing to return those from your program.

To be safe limit exit status codes to 0-127, as that is most portable, at least that is implied by http://docs.python.org/library/sys.html#sys.exit.

The C exit status is put into the bash $? variable after execution, but bash uses 127 to indicate 'command not found' so you may want to avoid that. Bash reference page.

Bash also uses 128-255 for signals - they indicate the process was killed with a signal: exit code = 128 + signal number. So you might be able to get away with using numbers close to 255 as it unlikely that signal numbers will go that high.

Beyond those common guide-lines there are many attempts to define what different numbers should mean: http://tldp.org/LDP/abs/html/exitcodes.html.

So it you want to return an arbitrary integer from your program, it's probably best to print it to stdout, and capture it with VALUE=$(program) from your bash script.



回答2:

The return value of main (i.e. the exit status of the application) is limited to the range [0, 255] on *NIX. 1000 is out of range, and the OS treats it as 0, presumably.



回答3:

In Unix-land the return value of main is limited because exit there is limited to the range of an 8-bit byte.

In Windows there is a single value, STILL_ACTIVE with value 259, that is best avoided as process exit code.

Other than that, in Windows you can return a 32-bit code such as an HRESULT and that is commonly done.