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?
Asked
Active
Viewed 103 times
2

DLWHI
- 71
- 5
-
2What OS are you using? – Thomas Matthews Apr 07 '21 at 23:03
-
2Please provide a [mcve]. – Thomas Matthews Apr 07 '21 at 23:03
-
I don't understand why you are using `exit()`. – Thomas Matthews Apr 07 '21 at 23:04
-
@ThomasMatthews i'm using ubuntu. I need exit to terminate process and recieve termination code – DLWHI Apr 07 '21 at 23:05
-
You can only **portably** call `exit()` with one of the values `EXIT_FAILURE`, `EXIT_SUCCESS`, and `0`. – Pete Becker Apr 08 '21 at 00:02
1 Answers
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