Given code like this...
int main(int argc, char **argv) {
pid_t pid;
int res;
pid = fork();
if (pid == 0) {
printf("child
");
exit(1);
}
pid = wait(&res);
printf("raw res=%d
", res);
return 0;
}
...the value of res
will be 256
. This is because the return value from wait
encodes both the exit status of the process as well as the reason the process exited. In general, you should not attempt to interpret non-zero return values from wait
directly; you should use of the WIF...
macros. For example, to see if a process exited normally:
WIFEXITED(status)
True if the process terminated normally by a call to _exit(2) or
exit(3).
And then to get the exit status:
WEXITSTATUS(status)
If WIFEXITED(status) is true, evaluates to the low-order 8 bits
of the argument passed to _exit(2) or exit(3) by the child.
For example:
int main(int argc, char **argv) {
pid_t pid;
int res;
pid = fork();
if (pid == 0) {
printf("child
");
exit(1);
}
pid = wait(&res);
printf("raw res=%d
", res);
if (WIFEXITED(res))
printf("exit status = %d
", WEXITSTATUS(res));
return 0;
}
You can read more details in the wait(2)
man page.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…