- URL: https://www.laruence.com/en/2012/02/01/2503.html
- Please include attribution when republishing.
Today someone asked a question on Weibo: using:
string exec ( string $command [, array &$output [, int &$return_var ]] )
to call a program, and the program exits with -1, but why does PHP get 255?
Simply put, the reason is that exit, or the return in the main function, can only use values between 0~255. The unsigned value of -1 is 255.
So how about the more complex explanation?
We know that in the Shell, running a command or a program is done by forking a child process (and then exec), and this program's exit code is collected by the Shell (the parent process) via wait, and then reported to us.
pid_t wait(int *statloc);
And for wait, for historical reasons, it returns a 16-bit integer through statloc (there are also 32-bit representations now, but they remain compatible with the existing design). In these 16 bits, the high 8 bits are the program's exit value (exit, or return), and the low 8 bits represent the signal that caused the program to exit (one of the bits indicates whether a Core file was produced). If the program exited normally, then the low 8 bits are 0[1].
So, if we return -1, and because we exited normally, the child-process exit status collected by the Shell through wait is:
11111111 00000000
And the high 8 bits, as unsigned, is 255.
In addition, as a supplement, in the Linux built-in Shell commands, many follow a convention for exit status codes, where the specific values correspond to meanings[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 |
Be First to Comment