我正在尝试使用posix_spawn()
生成一个子进程。我给出了可执行文件的名称(存在),但是posix_spawn()
创建了一个僵尸进程(我在ps
中搜索该进程,它显示为<defunct>
)。即使我指定了不存在的可执行文件名称,僵尸进程也会被创建。
我的问题是我需要知道该进程是否成功生成,但是由于posix_spawn
返回0(成功)并且子进程的ID有效,因此无法通知错误发生了。
这是我的代码(P.S.可执行文件“虚拟”不存在):
#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;
}
答案 0 :(得分:0)
子进程成为僵尸意味着它已经完成/死亡,您需要使用wait/waitpid
获得退出状态。
#include <sys/wait.h>
//...
int wstatus;
waitpid(pid,&wstatus,0);