jacob navia said:
It is the right thing to do. You should just document the error
code with its meaning, and if possible and stdin is not redirected
print some error message.
Some systems will truncate the error return, but keeping within
1 to 127 should be probably safe on all systems, i.e. a positive
8 bit number.
No, it's not the right thing to do, at least not if you care about
portability.
For example, on one system I use, an errno value of 21 is "EISDIR",
described as "Is a directory". (For example, you might get this if
you pass a directory name to fopen().) How do you know that returning
a value of 21 from main(), or calling exit(21), sends a failure
indication to the invoking environment? I've worked on systems where
exit(21) would indicate *successful* termination. And EISDIR might be
some other number on another system, or it might not be defined at
all, making the interpretation of the program's exit status completely
system-specific.
The same system that defines EISDIR as 21 defines errno values up to
131.
Even if you're willing to limit yourself to a single operating system
(though the OP implied no such willingness), on the systems I use
there is *no* convention of using errno values as returned results
from main. Both coincidentally use 0 to indicate "no error", but
that's where the similarity ends. On Unix-like systems, for example,
'exit(1)' often indicates a non-specific failure. If I saw a program
terminate with an exit status of 1, it would never occur to me to
assume that it had died due to an EPERM ("Operation not permitted")
error (EPERM happens to be defined as 1).
errno values denote failure modes for individual function calls. They
can be used to construct error messages, using perror() or strerror().
And what exit status do you return for a program error that doesn't
correspond to any errno value, such as a missing command-line
argument?
For portable code, use EXIT_FAILURE to denote failure, 0 or
EXIT_SUCCESS to denote success. If a function fails and sets errno,
use perror() or strerror() to construct an error message (but you may
or may not want to show such a message to the user). If you need to
indicate more than one kind of failure in your program's exit status,
you'll need to document which results mean what -- and your choice of
values is likely to depend on the operating system's conventions.
(In a language with stronger typing, errno and the argument to exit()
would have distinct and incompatible types, but that's not really an
option for C.)