创建一个有 4 个子进程的进程树

标签 c unix fork

我在创建此进程树时遇到问题。

Process Tree

这是我的代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> 
#include <sys/types.h>
#include <sys/wait.h>

int main ()
{
    int i;
    printf("\n [ID = %d] I am the root parent \n", getpid());
    for(i=0;i<4;i++)
    {
        pid_t ret=fork();
        if(ret <0) //eror occured
        {       
            printf("Fork Failed \n");
            return 1;
        }
        else if (ret == 0){
            printf("\n [ID =%d] My parent is [%d]\n", getpid(), getppid());
        }
        else
        {
            wait(NULL);
            exit(0);
        }
    }

    return 0;
}

这是我的输出

[ID = 4478] I am the root parent 

 [ID =4479] My parent is [4478]

 [ID =4480] My parent is [4479]

 [ID =4481] My parent is [4480]

 [ID =4482] My parent is [4481]

当我画出这个草图时,它只是一个链式进程树。

p
|
C1
|
C2
|
C3
|
C4

我尝试了其他方法来写这篇文章,但这已经接近生出四个 child 了。我在其他尝试中得到了 6 分。

最佳答案

你的缺陷在于程序本身的逻辑。首先,您考虑创建一个具有 4 次迭代的循环,而实际上您只希望父进程中有 2 个子进程。但是,当 fork成功 ( ret > 0 ) 您正在调用 wait(NULL); exit(0);这将停止 for循环并退出一次进程wait停止悬挂。当 children forked ,它们将位于 for 内也循环自己。如果循环没有陷入wait(NULL); exit(0);声明你会遇到更大的困惑,父进程有 4 个子进程,子进程有 3 到 0 个子进程,孙子进程有 2 到 0 个子进程,等等..

你需要的是这样的:

for(i = 0; i < 2; ++i){
  pid_t ret = fork();

  if(ret < 0){
    printf("Fork Failed!\n");
    return 1;
  } else if(ret == 0) { //Children process
    pid_t children_ret = fork();

    if(children_ret < 0){
      printf("Fork Failed!\n");
      return 1;
    } else if(children_ret == 0) { //Grandchildren process
      //... Do whatever you want on the grandchildren process
      exit(0);
    }

    //... Do whatever you want on the children process
    wait(NULL);
    exit(0);
  }
}
//... Do whatever you want on the parent process
wait(NULL);
exit(0);

请注意 exit对子进程和孙进程的调用非常重要。这是因为所有进程共享相同的代码,因此如果它们不在这些点上退出,它们将继续运行您拥有的其余代码(即:孙子进程将运行子代码和父代码)。

关于创建一个有 4 个子进程的进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48663589/

相关文章:

c - 如果在 for 循环中创建子进程的 if 语句中有 break,循环是否不再执行?

c - 管道/ fork 有问题。说明书看不懂一半(man)

c - 试图理解c中的死锁

c - 接收字符串消息时出现段错误

c - 在这种情况下哪种操作系统概念应该更好

unix - 单个邮件unix中带有多个附件的mutt命令

c - 我的程序似乎没有终止;为什么?

c - 在 window/openGL 上显示的图像已损坏

c++ - 如何解决 .cpp 和 .hpp 文件中的 calloc() 错误?

bash - 遍历子目录并对某些文件执行 awk 脚本