exit(0) versus exit(1)

What is the difference between using exit(0) and exit(1) to exit a program? Which should I use?

You normally use exit(0) if everything went ok. But if your program detects an error and decides to abort, you would use exit(1). Or you might use exit(1), exit(2), etc, with each exit code meaning some specific error.

For normal exits use 0 (recommended)
and for abnormal program termination or incomplete ones use 1 (recommended)

these exit status are indication to the environment from which the program has run about the status of exit of the program

What to do you want to tell your parent?

The rules is generally if all went went and you did what you were told (as all children should) then return 0.

If something went wrong then return non-zero, preferably between 1 and 127.

This is termed the exit code of a process and in a shell becomes the "$?" value.

This allows you to do the following

if myprogram
then 
      echo all went well
else 
      echo bad things
fi

Thanks for the tips.

hi enuenu,
actualy you should use

#include <stdlib.h>

exit(EXIT_SUCCESS);
exit(EXIT_FAILURE);

just my 2 cents :slight_smile:

Thanks, I am still investigating (this and much more).

can it be bigger than 127?
thanks

It can in many cases. Porter is saying <= 127 becasue that is the largest signed value which you can have in a single byte.

Look in your /usr/include directory (or wherever your standard C headers are)
and find sysexits.h It is part of a lot of distributions.

Read the header file - it gives some proposed standards for exit values that are meaningful and consistent. You will find that a lot of programs return values like 64. It comes from sysexists.h

No sysexits.h file:
http://www.freebsd.org/cgi/man.cgi?query=sysexits&apropos=0&sektion=0&manpath=FreeBSD\+4.3-RELEASE&format=html