子进程在分叉和执行后变得失效

Child process becomes Defunct after fork and exec

本文关键字:失效 执行 分叉 子进程      更新时间:2023-10-16

我正在学习fork和exec,并使用fork和execlp创建多个子进程,我在子进程中所做的只是让它睡觉。基本上,我只想让我所有的孩子都活着。但是一旦我启动我的监视器.cpp它创建的进程,所有孩子都会立即退出,他们确实不复存在!

监视哪个分支多个子项

#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
for(size_t i=0; i<std::stoi(argv[1]) ; ++i)
{
int pid = fork();
if(pid == 0)
{
execlp("child", "child", std::string(std::to_string(i)).c_str(), (char *)0);
std::cout << "child exiting " << std::endl;
exit(1);
}
else if(pid > 0)
{
std::cout <<"child started with " << pid << std::endl;
}
else
{
std::cout << "fork failed" << std::endl;
}
}
while(true)
{
std::this_thread::sleep_for(std::chrono::seconds(100000));
}
return 0;
}

儿童代码

#include <iostream>
#include <thread>
#include <chrono>
int main(int argc, char* argv[])
{
std::cout << " child started with id " << argv[1] << std::endl;
std::cout <<"child sleeping " << argv[1] << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1000));
std::cout << "child exiting " << argv[1] << std::endl;
return 0;
}

输出:

child started with 1834
child started with 1835
child exiting 
child started with 1836
child exiting 
child started with 1837
child started with 1838
child started with 1839
child exiting 
child started with 1840
child started with 1841
child exiting 
child started with 1842
child started with 1843
child exiting 
child exiting 
child exiting 
child exiting 
child exiting 
child exiting

ps -ef 将我的所有子进程显示为已停用,即使我的父进程还活着。

你能解释一下我错过了什么吗?

从"execlp"手册页:

exec(( 函数仅在发生错误时返回。返回值为 -1,并且 errno 设置为指示错误。

由于"child exiting"在两个地方打印,因此它是否退出并不明显。您需要检查它的返回值并errno

您需要在子进程退出时收获它们。这是使用waitwaitpid调用完成的。

在父进程完成此操作之前,它们将作为已失效/僵尸进程可见。(init,进程 1,负责在退出后收获所有没有父进程的进程(