问题
On TutorialsPoint.com, exit is passed the value 0
, while people often pass it 1
. I've even seen exit(3);
What do the different values mean?
回答1:
By convention, a program that exits successfully calls exit
(or returns from main
) with a value of 0. Shell programs (most programs, actually) will look for this to determine if a program ran successfully or not.
Any other value is considered an abnormal exit. What each of those values mean is defined by the program in question.
On Unix and similar systems, only the lower 8 bits of the exit value are used as the exit code of the program and are returned to the parent process on a call to wait
. Calling exit(n)
is equivalent to calling exit(n & 0xff)
From the man page:
The
exit()
function causes normal process termination and the value ofstatus & 0377
is returned to the parent (seewait
(2)).
回答2:
The only portable values to pass to exit
are 0
, EXIT_SUCCESS
, and EXIT_FAILURE
. The latter two are macros defined in <stdlib.h>
, the same header that declares the exit
function.
Both 0
and EXIT_SUCCESS
conventionally indicate that the program succeeded. EXIT_FAILURE
indicates that it failed somehow. (EXIT_SUCCESS
is almost certainly defined as 0
.)
For UNIX-like systems, EXIT_FAILURE
is defined as 1
, and exit(1)
is also common (though a bit less portable). Some operating systems might use a different convention; for example OpenVMS uses even values for failure and odd values for success, with some special-case code to map exit(0)
to a failure status.
Other values may be used by some programs to indicate different kinds of failure. For example, the grep
command uses 0
if a match was found, 1
if no match was found, and 2
if some other error occurred.
回答3:
int main()
{
exit(0);
}
is the same as
int main()
{
return 0;
}
The return values are basically error codes:
0
(or macroEXIT_SUCCESS
defined in"stdlib.h"
) means successful program termination1
(or macroEXIT_FAILURE
defined in"stdlib.h"
) means program termination because of failure
Other error codes are also possible, but they are system dependent thus not part of the C standard, i.e. they are not portable.
回答4:
Exit values are program dependent. The biggest consideration is probably that most (all?) shells consider a return value of zero to mean success. Any other value indicates failure.
来源:https://stackoverflow.com/questions/36904391/what-int-values-are-relevant-for-exit-in-c