问题
I exit with -1 in the child, but the parent picks up 255 instead. Is there a way to make the parent recognize -1 instead? Here is my code
pid = fork();
// if fork fails
if (pid < 0){
exit(EXIT_FAILURE);
}
else if (pid == 0){
// purposely exit
_exit(-1);
}
else{
int status;
int corpse = wait(&status);
if (WIFEXITED(status))
{
int estat = WEXITSTATUS(status);
if (estat == 0){
printf("Command was successfully executed\n");
}
else{
printf("Error: child exited with status %d\n", estat);
}
}
else
printf("signalled\n", corpse);
回答1:
From wait:
WEXITSTATUS(status)
returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should be employed only if WIFEXITED returned true.
The least significant 8 bits of -1
is 0xFF
(255
).
回答2:
the status returned from function wait
contains information of not only the exit code of the child process, but also contains the termination reason, etc.. thus, it is impossible to get the exact exit code of the child process, and only the least 8 bits of the child exiting code is represented.
回答3:
status will be 0xFF00 after wait().
来源:https://stackoverflow.com/questions/26435730/forked-child-exits-with-1-but-wexitstatus-gets-255