Why is the exit code obtained by the exit (- 1) or return (- 1) shell 255


Now I wrote a hello world program. Let’s have a look:

// filename: main.c
 #include <stdio.h>
 int main(void)
   printf("hello wolrd!\n");

Compilation execution: GCC main. C & &. / a.out

Now let’s look at the return value of the last execution process returned in the current shell. Is it “- 1”?

[email protected]:~/Desktop $GCC main. C & &. / a.out

hello world!

[email protected]:~/Desktop $echo $?


Ah, why “255” in the end? Call a program, the program exits – 1, and the result is not “- 1”?

The following references are from:http://www.laruence.com/2012/02/01/2503.html

This problem is simply because the return in the exit or main function can only use values between 0 and 255. The unsigned value of – 1 is 255

What about the more complicated one?

We know that in the shell, a command and a program are executed by fork a child process (and then exec), and the exit code of the program is collected by the shell (parent process) through wait and then reported to us

pid_twait(int *statloc);

As for wait, for historical reasons, it will return a 16bit interge through statloc (now it is also represented by 32 bits, but it will be compatible with existing designs). Among the 16bits interge, the upper 8 bits are the value of program exit (exit, or return), and the lower 8 bits indicate the signal causing the program exit (one bit indicates whether a core file is generated), If the program exits normally, the lower eight bits are 0 [1]

Therefore, if we return – 1 and we exit normally, the exit status of the child process collected by the shell through wait is:

11111111 00000000

The top eight, as unsigned, is 255

In addition, in the built-in shell commands of Linux, many will abide by the agreement of an exit status code. The specific value corresponds to the meaning [2]:

Exit Code Number Meaning Example Comments
1 Catchall for general errors let “var1 = 1/0″ Miscellaneous errors, such as ”divide by zero” and other impermissible operations
2 Misuse of shell builtins (according to Bash documentation) empty_function() {} Seldom seen, usually defaults to exit code 1
126 Command invoked cannot execute   Permission problem or command is not an executable
127 “command not found” illegal_command Possible problem with $PATH or a typo
128 Invalid argument to exit exit 3.14159 exit takes only integer args in the range 0 – 255 (see first footnote)
128+n Fatal error signal ”n” kill -9 $PPID of script $? returns 137 (128 + 9)
130 Script terminated by Control-C   Control-C is fatal error signal 2, (130 = 128 + 2, see above)
255* Exit status out of range exit -1 exit takes only integer args in the range 0 – 255