4

I have a simple program to test exit codes:

int main() { 
    return 2000;
}

In the terminal if I run the program then type:

echo $?

the terminal replies with 208. What? Why would it do that?

sircodesalot
  • 11,231
  • 8
  • 50
  • 83
  • Exit codes only range through 256? Why force main to return `int` then? – sircodesalot Oct 01 '13 at 02:23
  • Because the language says so... (the language requires `main` to return an `int`) – Mysticial Oct 01 '13 at 02:24
  • @Mystical I think the OP was getting at why the _standard_ says so. – Cole Tobin Oct 01 '13 at 02:29
  • Inherited from 'C', for the same reason that "toupper" etc take an int when the values are actually chars. 'int' was at one point a catch-all, generic, "a number". It's gotten a lot bigger since then. – kfsone Oct 01 '13 at 02:58

3 Answers3

6

While the return value of main is an int (generally 32 bits), only 8 bits of the exit code are communicated out to the rest of the operating system.

As Mystical pointed out, 2000 % 256 = 208.

In Linux, a parent process retrieves the status of a child process via a call to wait or waitpid (usually after the child exits). That call provides a status value - encoded in this int is the exit code of the child, along with several other fields, indicating if/how the child exited, etc. The exit code is extracted via the WEXITSTATUS macro.

int status;
waitpid(childpid, &status, 0);
if (WIFEXITED(status))
    printf("Child exited with code %d\n", WEXITSTATUS(status));

It's interesting to note that I don't really see this mentioned in any of the man pages, though!

But it's very apparent if we take a look at the kernel:

In kernel/exit.c, we see where the exit system call is defined:

888  SYSCALL_DEFINE1(exit, int, error_code)
889  {
890      do_exit((error_code&0xff)<<8);
891  }

You can see right there, that the int error code is truncated to eight bits, and stuffed into bits 15:8 of the code passed to do_exit.

Related questions:

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
2

UNIX error codes are a byte big, so your value is chopped down to its remainder mod 256, namely 208.

Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
Jakob Weisblat
  • 7,450
  • 9
  • 37
  • 65
2

The C standard only defines three return codes: 0, EXIT_SUCCESS and EXIT_FAILURE. (Normally, EXIT_SUCCESS is 0, but I don't think that is technically required.)

If the status return is 0 or EXIT_SUCCESS, then "an implementation-defined form of the status successful termination is returned [to the host environment]". If it's EXIT_FAILURE, then "unsuccessful termination" is returned.

Any other return code is implementation-defined. Your implementation defines that a status return of 2000 returns 208 to the host-environment. It's completely within it's rights to do so.

rici
  • 234,347
  • 28
  • 237
  • 341