在C中使用fork()创建特定的进程树

标签 c linux bash tree

我不知道如何解决这个问题。我需要在 C 中使用 fork()ifelse 创建一个进程树。 这棵树需要看起来像这样:

a.out---a.out---a.out
     | 
     |--a.out---a.out---a.out
     |
     |--a.out---a.out---a.out
     |
     |--a.out

我已经有了这个:

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


int main (void){
    if(fork()){
        if(fork()){}          
        else{}
        if(fork()){}
        else{fork();}
    }
    else{}

    pause();
    return 0;
}    

这将创建一个如下所示的进程树:

a.out---a.out
     | 
     |--a.out---a.out---a.out
     |
     |--a.out---a.out

最佳答案

这看起来应该可以做到:

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

int main() {
   if (fork()) {
      // parent
      if (fork()) {
         // parent
         if (fork()) {
            // parent
            if (fork()) {
               // parent
            }
            else {
               // child 4
            }
         }
         else {
            // child 3
            if (fork()) {
               // child 3
            }
            else {
               // child 1 of child 3
               if (fork()) {
                  // child 1 of child 3
               }
               else {
                  // grandchild 1 of child 3
               }
            }
         }
      }
      else {
         // child 2
         if (fork()) {
            // child 2
         }
         else {
            // child 1 of child 2
            if (fork()) {
               // child 1 of child 2
            }
            else {
               // grandchild 1 of child 2
            }
         }
      }
   }
   else {
      // child 1
      if (fork()) {
         // child 1
      }
      else {
         // child 1 of child 1
      }
   }

   pause();
   return 0;
}

理想情况下,您可以添加一些存储各种 PID 的变量,并将它们与它们的父级一起打印出来,以便您可以看到它。

关于在C中使用fork()创建特定的进程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24071471/

相关文章:

linux - 具有重复行的 csv 文件的最佳压缩

bash - bash 脚本中 stderr 的临时重定向

bash - 如何在 Mac OS X 上的 bash 脚本中获取默认浏览器名称

c - 在C中插入AVL树

objective-c - 为什么 readline() 在控制台中输入回显?

c - GTK:设置对话框的默认按钮

具有不同参数的函数的 C 冲突类型

linux - 无法创建连接,pgadmin 3 与 ubuntu 中的服务器

python - 是否可以在开发过程中阻止 Django 创建 .pyc 文件?

linux - 将 awk 操作存储在变量中