fork()不会创建孙子辈的产品

问题描述 投票:0回答:1

我想使用fork()来创建一个子进程,继续创建另一个子进程(父进程的孙子进程)。但我似乎无法用这段代码创建一个孙子进程。这里有什么问题吗?

#include <stdio.h>
#include <unistd.h>

void child_A_proc()
{
  while (1)
  {
    fprintf(stdout, "%s", "A");
    fflush(stdout);
  }
}

void parent_proc()
{
  while (1)
  {
    write(1, "B", 1);
  }
}

void child_of_child_A_proc() 
{
  while (1)
  {
    fprintf(stdout, "%s", "C");
    fflush(stdout);
  }
}

int main(void)
{
  if (fork() == 0){
    child_A_proc();
    if (fork() == 0)
      child_of_child_A_proc();
    else 
      child_A_proc();
  }
  else
    parent_proc();

  return 0;
}
c fork
1个回答
3
投票

检查是否有调用不返回的函数。

  if (fork() == 0){
    child_A_proc();
    /* unreachable */
    if (fork() == 0)
      child_of_child_A_proc();
    else 
      child_A_proc();
  }
© www.soinside.com 2019 - 2024. All rights reserved.