2

I have a multi-process program that runs 4 processes that should return exit value.
But when process reaches exit(int) line it actually returns other value to wait()
For example: exit(1) will give value of 256 to wait()
exit(3) - 768
exit(4) - 1024
and so on. I guess it returns a value in exit(int) multiplied by 256.
Why this happens and how to fix(?) this?

DLWHI
  • 71
  • 5

1 Answers1

6

You cannot directly consume the value provided by wait as it encodes additional information in an implementation-defined manner. You must use the WEXITSTATUS macro if the process exited and/or other macros like WTERMSIG or WSTOPSIG if a signal was involved. Adapted from man 2 wait:

int wstatus;
w = wait(&wstatus);
if (w < 0) {
    perror("wait");
    exit(EXIT_FAILURE);
}

if (WIFEXITED(wstatus)) {
    printf("exited, status=%d\n", WEXITSTATUS(wstatus));
} else if (WIFSIGNALED(wstatus)) {
    printf("killed by signal %d\n", WTERMSIG(wstatus));
} else if (WIFSTOPPED(wstatus)) {
    printf("stopped by signal %d\n", WSTOPSIG(wstatus));
} else if (WIFCONTINUED(wstatus)) {
    printf("continued\n");
}

On my system (Ubuntu through WSL), WEXITSTATUS is defined as:

#define __WEXITSTATUS(status)   (((status) & 0xff00) >> 8)
...
# define WEXITSTATUS(status)    __WEXITSTATUS (status)

This matches up with what you observe, where the obtained value is 256 times the expected exit code. However, because the encoding is defined by the implementation, you should not make this assumption yourself.

nanofarad
  • 40,330
  • 4
  • 86
  • 117