首页 > 解决方案 > 子进程在 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 将我的所有子进程显示为已失效,即使我的父母还活着。

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

标签: c++linuxforkexec

解决方案


从“execlp”手册页:

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

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


推荐阅读