1

I am trying to exit my main function with a certain exit number, but it always exits with 0. For example, the code:

printf("command exited with error: %i\n", commandExitError);
if(commandExitError > 0)
  exit(commandExitError);

if(openError > 0)
  exit(openError);
printf("I shouldn't see this if there was an error");
return 0;

has the strange behavior that if commandExitError is 0, but openError is 1, then it exits with error 1. However, if commandExitError is greater than zero, it still exits with 0! For example, this is some output with commandExitError > 0:

command exited with error: 512

Note that we never reached the print statement "I shouldn't see this...." Then, getting the exit status of my program, echo $?

0

We see that my program still exits with 0 although it should clearly exit with 512.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
patrickd
  • 275
  • 3
  • 14

2 Answers2

5

according to man

The exit() function causes normal process termination and the value of status & 0377 is returned to the parent

octal 377 is decimal 255

512 & 255 = 0
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
1

I'm not sure if the range of possible exit codes is defined by any standard, but the GNU C library (as an example) only accepts values in the range 0 to 255. Reference

paddy
  • 60,864
  • 6
  • 61
  • 103