从 children 分叉 3 grandchildren 时遇到问题,顺序和 PID 和 PPID 不正确

trouble with forking 3 grandchildren from children, order and PID and PPIDs not right

您好,我有一个关于使用 fork() 创建更多 children 的问题,该问题基于我之前提出的一个问题

我希望我的输出看起来像这样(#s 已简化,仅用于说明顺序)

[grandpa]hi am I PID 1234 and I come from ####(dont care what this number is)
  [dad] hi i am PID 2111 and I come from PPID 1234
    [son] hi i am PID 3111 and I come from PPID 2111
    [son] hi i am PID 3112 and I come from PPID 2111
    [son] hi i am PID 3113 and I come from PPID 2111
  [dad] hi i am PID 2112 and I come from PPID 1234
    [son] hi i am PID 3111 and I come from PPID 2112
    [son] hi i am PID 3112 and I come from PPID 2112
    [son] hi i am PID 3113 and I come from PPID 2112
  [dad] hi i am PID 2113 and I come from PPID 1234
    [son] hi i am PID 3111 and I come from PPID 2113
    [son] hi i am PID 3112 and I come from PPID 2113
    [son] hi i am PID 3113 and I come from PPID 2113

但我的输出是这样的:

除了最后一个和大多数 PID 之外,关于爸爸 ppid 的最后似乎没问题。我不知道为什么有一个儿子,然后是5个,然后是3个儿子。这是我的代码:

int grandforking(null)
{
    Gen1 (null);       
    return 0;
}

int Gen1 (null)
{    
  void about(char *);
  int i=0;
  int j=0;  
  about("grandpa");    
  for(i = 0; i < 3; i++ )
  {
        pid_t child = 0;
        child = fork();
        if (child < 0) 
        { //unable to fork error
            perror ("Unable to fork");
            exit(-1);
        }    
        else if (child == 0)
        { //child process
             Gen2 (null);
             exit(0);
        }    
        else 
        { //parent process    
              //(do nothing)
        }    
  }   
  for(j = 0; j < 3; j++ )
  {
     wait(NULL);//wait for parent to acknowledge child process
  }
return 0;
}

int Gen2 (null)
{   
  int i=0;
  int j=0;
  about("dad");
  for(i = 0; i < 3; i++ )
  {
        pid_t child = 0;
        child = fork();
        if (child < 0)
        { //unable to fork error
            perror ("Unable to fork");
            exit(-1);
         }    
         else if (child == 0)
         { //child process
             about ("son");
             exit(0);
         }   
         else 
         { //parent process
            //(do nothing)
         }
  }
  for(j = 0; j < 3; j++ )
  {
    wait(NULL);//wait for parent to acknowledge child process
  }
   return 0;    
 }

一旦进程启动,调度器就可以并且将运行它们以它希望的任何顺序进行。如果您有多个处理器,这包括同时 运行多个。 (现在和每个人一样。)

它当然可以启动一个child,运行那个child一会儿,然后才回到parent打印消息。

如果在 parent 产生它的 children 之前有标识 printf,你的排序会稍微好一些。

但获得同步排序的唯一方法是执行以下操作:

  • 表明自己
  • 循环开始
    • 启动 child
    • 等待child完成
  • 全部children完成后退出