Assume the following C snippet showing a piece of error handling:
#include <sysexits.h> #include <stdio.h> … int main(int argc, char argv*[]) { int retval=0; … if(3!=argc) { /* wrong number of arguments */ retval |= EX_USAGE; const int fprintf_retval = fprintf(stderr, "Bad syntax.\n"); if (0>=fprintf_retval) retval |= … Hmm … ; } … return retval; } Which error constant from sysexits.h should be placed instead of “… Hmm …”? We can say EX_OSERR (a failure to print an error message shows that something is off, though not necessarily deep in the operating system), or EX_IOERR (it's an output error, though not necessarily into a file), or EX_SOFTWARE (fairly general, but the reason for a failure to print an error typically lies outside the C program, and the error might relate to the operating system). Based only on the comments in sysexits.h, neither of the three constants fits perfectly. So what's the convention?
EDIT: In the scope of this question, we assume that the programmer does want to discern between certain kinds of errors via the exit code, and that more than one error can occur.
echoreturns 1, andgrepreturns 2, same as for other errors (since for grep, 1 means a succesful run with no match found).sysexits.hdefines exit codes starting at 64 on both Ubuntu and FreeBSD and I think I've never seen a program return any such. Though it looks like that's from the BSDs, and I haven't really used them at all. Perhaps the existing utilities that do use the custom would work as a reference.|=there to begin with? I.e. that the values form a bit map? Also, this has nothing to do with Linux as suchgrep foo 2>> /nonexistent_fileas a nonroot, regular user yields exit code 1 on my system. We use “bitwise or” as there may be multiple errors. Say, a scanning program accepts two arguments: the scanner name and the output-file name. The first error might be a wrong scanner name, and the second that the output-file name has not been supplied. Of course, you have 8 bits only, so only 7 possible classes of errors (as the upper bit is reserved for signals), and sysexits.h takes 5 bits already, so you have only 7-5=2 bits left at your pleasure. Still, better than nothing.SIGCHLDsignal handler: "The exit value insi_statusshall be equal to the full exit value (that is, the value passed to_exit(),_Exit(), orexit(), or returned frommain()); it shall not be limited to the least significant eight bits of the value." I don't believe Linux supports that, however