Why can't I return bigger values from main function?

微笑、不失礼 提交于 2019-11-30 08:10:03

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!