为什么子进程退出后 WIFEXITED return false?

Why does WIFEXITED return false after child process exits?

我有这个简单的程序可以创建一个立即调用 exit() 的子进程。因此,在父进程中,我期望 WIFEXITED(status) 的计算结果为 true,但事实并非如此。相反,WIFSTOPPED(status) 计算为 true 并打印 "stopped"。谁能解释为什么我会出现这种行为?我在 OS X 上 运行 并使用 gcc 进行编译。谢谢!

#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);
}

你有 child 和 parent 的倒序逻辑。 parent 正在立即退出,child 正在调用 wait。由于 child 没有 children,wait 返回错误(并且没有触及 status),因为 child 没有 children (ECHILD),那么您正在测试 status 的(未初始化的)值并对其进行操作,从而导致未定义的行为。

变化:

else if (pid == 0)

至:

else if (pid > 0)

它应该按预期工作。