On a *NIX machine, the variable '$?' has the exit code returned by the last executed process. For example:
srikanth@workstation - [~] $ find . -nam "*.c" # Intentionally trying a wrong option find: invalid predicate `-nam' srikanth@workstation - [~] $ echo $? 1 # >0, process failed srikanth@workstation - [~] $ find . -name "*.c" ./test.c srikanth@workstation - [~] $ echo $? 0 # Process execution successful srikanth@workstation - [~] $
But too often I've seen programmers not taking care of the exit codes for the applications or some small-time utility programs they write. I've done it myself when I started out programming partly because I didn't know the significance of the exit codes. But they are very helpful.
Sometimes you've to spawn a new process from your program to accomplish something 'cause you don't have an API exposed for it in your language. At these times, the exit code returned by the child process can be extremely useful.
So, when writing some new command line utility or an application, remember to:
- Always return an exit code: 0 for success; 1 <= exit_code <= 255 for failure
- Don't return negative exit codes: I've seen this in some code; I didn't know it was invalid till someone had an issue with it. At least on UNIX, the valid exit codes are from 0 to 255
- Document the exit codes: Like 1 for database failure, 2 for mis-configuration, etc.
2 comments:
There is a standardization in the return code for the HTTP response, like 200 for OK, 404 NOT FOUND.
For those that don't have a recommendation, I think Programmers have to take care of it, as a coding style or practice.
Good Observation Srikanth.
Although exit codes do have their uses, exit code by itself is not really useful to debug and fix the root cause of the error. Unfortunately, they only tell what happened but never why it happened.
For languages that support it, exceptions are be a much better way to figure out why the failure happened and gives a certain direction to fix your code.
Post a Comment