c++ - 子进程在 fork 和 exec 后变为 Defunct
问题描述
我正在学习 fork 和 exec 并使用 fork 和 execlp 创建多个子进程,我在子进程中所做的就是让它休眠。基本上我只是希望我所有的孩子都还活着。但是,一旦我启动创建进程的monitor.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
.
推荐阅读
- mongodb - mongodb连接是同步的吗?
- verifiable-c - forward_call 遇到问题 - “没有适用的策略”
- node.js - Node.js 本机插件的不同实例之间的全局共享数据?
- java - 如果这包括那个(java密码生成器)
- c++ - 我可以将winCC OA与虚幻引擎连接吗?
- python - 如何在python中添加列表值
- rust - Unicode 代码点到 Rust 字符串
- python - 对于给定的字典键,获取所有下属作为列表
- javascript - Ajax 显示模式未从第一次单击触发
- html - 是否有一个 CSS 选择器来检查输入是否有任何文本?