的posix_spawn创建一个僵尸进程,并返回成功

问题描述 投票:1回答:1

我想都会产生posix_spawn()子进程。我给可执行文件名称(存在),但posix_spawn()创建一个僵尸进程(我搜索的过程中ps,它显示为<defunct>)。甚至当我指定一个不存在的可执行文件名称,创建僵尸进程。

我的问题是,我需要知道该进程是否成功与否产生了,但由于posix_spawn返回0(成功)和子进程的ID是有效的,我也没办法通知发生了错误。

这里是我的代码(附注:可执行的“虚拟”不存在):

#include <iostream>
#include <spawn.h>

extern char **environ;

int main()
{
    const char *args[] = { "dummy", nullptr };

    pid_t pid = 0;

    posix_spawn(&pid, "dummy", nullptr, nullptr, const_cast<char **>(args), environ);
    if (pid == 0)
    {
        // doesn't get here
    }
    else
        // this gets executed instead, pid has some value
        std::cout << pid << std::endl;
}

随着越来越状态:

#include <iostream>
#include <spawn.h>

extern char **environ;

int main()
{
    const char *args[] = { "dummy", nullptr };

    int status = posix_spawn(nullptr, "dummy", nullptr, nullptr, const_cast<char **>(args), environ);
    if (status != 0)
    {
        // doesn't get here
    }
    else
        // this gets executed, status is 0
        std::cout << status << std::endl;
}
c++ linux posix child-process spawn
1个回答
0
投票

子进程是一个僵尸意味着它结束/死了,你需要获得与wait/waitpid它的退出状态。

#include <sys/wait.h>
//...
int wstatus; 
waitpid(pid,&wstatus,0);
© www.soinside.com 2019 - 2024. All rights reserved.