25.6.2 Exit Status
When a program exits, it can return to the parent process a smallamount of information about the cause of termination, using theexit status. This is a value between 0 and 255 that the exitingprocess passes as an argument to exit
.
Normally you should use the exit status to report very broad informationabout success or failure. You can't provide a lot of detail about thereasons for the failure, and most parent processes would not want muchdetail anyway.
There are conventions for what sorts of status values certain programsshould return. The most common convention is simply 0 for success and 1for failure. Programs that perform comparison use a differentconvention: they use status 1 to indicate a mismatch, and status 2 toindicate an inability to compare. Your program should follow anexisting convention if an existing convention makes sense for it.
A general convention reserves status values 128 and up for specialpurposes. In particular, the value 128 is used to indicate failure toexecute another program in a subprocess. This convention is notuniversally obeyed, but it is a good idea to follow it in your programs.
Warning: Don't try to use the number of errors as the exitstatus. This is actually not very useful; a parent process wouldgenerally not care how many errors occurred. Worse than that, it doesnot work, because the status value is truncated to eight bits. Thus, if the program tried to report 256 errors, the parent wouldreceive a report of 0 errors—that is, success.
For the same reason, it does not work to use the value of errno
as the exit status—these can exceed 255.
Portability note: Some non-POSIX systems use differentconventions for exit status values. For greater portability, you canuse the macros EXIT_SUCCESS
and EXIT_FAILURE
for theconventional status value for success and failure, respectively. Theyare declared in the file stdlib.h.
This macro can be used with the
exit
function to indicatesuccessful program completion.On POSIX systems, the value of this macro is
0
. On othersystems, the value might be some other (possibly non-constant) integerexpression.
This macro can be used with the
exit
function to indicateunsuccessful program completion in a general sense.On POSIX systems, the value of this macro is
1
. On othersystems, the value might be some other (possibly non-constant) integerexpression. Other nonzero status values also indicate failures. Certainprograms use different nonzero status values to indicate particularkinds of "non-success". For example,diff
uses status value1
to mean that the files are different, and2
or more tomean that there was difficulty in opening the files.
Don't confuse a program's exit status with a process' termination status. There are lots of ways a process can terminate besides having it's programfinish. In the event that the process termination is caused by programtermination (i.e., exit
), though, the program's exit status becomespart of the process' termination status.