Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weirdly changing status codes [duplicate]

Tags:

c++

c

linux

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?

like image 595
sircodesalot Avatar asked Dec 26 '22 19:12

sircodesalot


1 Answers

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:

  • Any benefit in using WEXITSTATUS macro in C over division by 256 on exit() status?
like image 59
Jonathon Reinhart Avatar answered Jan 02 '23 13:01

Jonathon Reinhart