Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux,c++, negative exit codes, clarifiction?

In Linux, c++ can we return exit codes? i.e is this code valid:

int main()
{
  return -1;
}

The reason I am asking if this code is compiled and executed from bash/zsh, the return value would be 255, I thin this due to the fact that its using an 8 bit return code, and that implies that return codes are only allowed to be between positive.

Is this correct?

like image 388
Joe Avatar asked Feb 18 '26 11:02

Joe


1 Answers

The relevant system call is _exit(), and POSIX itself specifies that only the bottom 8 bits of the status given to _exit() are normally usable:

_exit(status)
The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available from wait() and waitpid();

Though it goes on to say that "the full value shall be available from waitid()", but on Linux, I seem to still get just the low eight bits.

like image 93
ilkkachu Avatar answered Feb 20 '26 01:02

ilkkachu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!