gpt4 book ai didi

c++ - 子进程在 fork 和 exec 后变为 Defunct

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:21 25 4
gpt4 key购买 nike

我正在学习 fork 和 exec,并使用 fork 和 execlp 创建多个子进程,我在子进程中所做的只是让它休眠。基本上我只希望我所有的 child 都活着。但是,一旦我启动创建进程的 monitor.cpp,所有子进程都会立即退出,并且它们会失效!

Monitor which forks multiple children

#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 将我所有的子进程显示为 Defunct,即使我的父进程还活着。

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

最佳答案

来自“execlp”手册页:

The exec() functions only return if an error has occurred. The return value is -1, and errno is set to indicate the error.

由于 "child exiting" 被打印在两个地方,如果它正在退出并不明显。您需要检查它的返回值和 errno

关于c++ - 子进程在 fork 和 exec 后变为 Defunct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com