I've got this simple program that creates a child process which immediately calls exit()
. So in the parent process I'm expecting WIFEXITED(status)
to evaluate as true
, but it's not. Instead, WIFSTOPPED(status)
evaluates as true
and "stopped" is printed. Can anyone explain why I'm getting this behavior? I'm running on OS X and compiling with gcc. Thanks!
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
int main(void)
{
int pid;
int status;
pid = fork();
if (pid < 0)
printf("fork failed\n");
else if (pid == 0)
{
wait(&status);
if (WIFEXITED(status))
printf("exited\n");
else if (WIFSTOPPED(status))
printf("stopped\n");
}
else
exit(0);
return (0);
}
You have the logic for the child and parent backwards. The parent is exiting immediately and the child is calling wait
. Since the child has no children, wait
is returning an error (and not touching status
) since the child has no children (ECHILD
), then you're testing the (uninitialized) value of status
and acting on it, resulting in undefined behavior.
Change:
else if (pid == 0)
to:
else if (pid > 0)
and it should work as expected.