子进程在分叉和执行后变得失效
Child process becomes Defunct after fork and exec
我正在学习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
。
您需要在子进程退出时收获它们。这是使用wait
或waitpid
调用完成的。
在父进程完成此操作之前,它们将作为已失效/僵尸进程可见。(init,进程 1,负责在退出后收获所有没有父进程的进程(
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 程序在执行程序的其余部分之前退出
- 为什么catch中的代码没有被执行
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 将执行、作业和WinAPI相乘
- 子进程在分叉和执行后变得失效
- OPENCL 1.2失效执行不起作用
- 对std::deque执行迭代器在容器两端插入或擦除后会失效