簡體   English   中英

子進程在fork和exec之后變為Defunct

[英]Child process becomes Defunct after fork and exec

我正在學習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

您需要在子進程退出時獲得其子進程。 這是使用waitwaitpid調用完成的。

在父級執行此操作之前,它們將作為defunc / zombie進程可見。 (init,進程1,負責在退出后獲得沒有父級的所有進程)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM