c - 如何在c中创建proc树

标签 c process tree proc

我有一个数字数组,它告诉每个父进程必须创建多少个子进程,或者更确切地说,树的结构是什么。

例如,如果数组包含 1 4 0 0 3,那么过程树如下所示 http://shrani.si/f/S/IW/8HrGEVJ/proctree.jpg

我认为这可以通过递归来解决,但我不知道如何读取数组并确定应该在哪里 fork 以及有多少子进程。另外,如果您的代码模板如下所示,如何从一个父级创建更多子级:

void recTreeProc(){

    /* create process */
    pid_t pid;
    pid = fork();

    if (pid == -1) {
            /* error */
            perror("fork failed");
            exit(EXIT_FAILURE);
    }

    else if (pid == 0) {
            /*  child process */
            //call recursion?
    }
    else {
            /* parent process */
            //wait for all the children to execute
            int status;
            (void)waitpid(pid, &status, 0);

    }

}

最佳答案

我无法帮助您实现树和数组的代码,因为我不明白这些值的含义,但对于多个 child ,您可以尝试这样做:

void recTreeProc() {

  /* create process */
  pid_t pid;
  int n = 0;
  int cpid[CHILD_NB];

  do {
     pid = fork();
     if (pid == -1) {
        perror("fork failed");
        exit(EXIT_FAILURE);
     }
     else if (pid) {
        cpid[n];
     }
     n++;
  } while(n < CHILD_NB && pid); // I want CHILD_NB childs
  if (!pid) {
   /* childs */
  }
  else {
        /* parent process */
        //wait for all the children to execute
        int status[CHILD_NB];
        n = 0;
        while (n < CHILD_NB) {
          (void)waitpid(cpid[n], &status[n], 0);
          n++;
        }
  }
}

关于c - 如何在c中创建proc树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23680102/

相关文章:

linux - 在linux上,如何等待多个子进程?

c - 用C写在管道上

c - 简单的 C 代码不起作用

c - 如何获取sem_wait()的返回值?

c++ - 处理创建进程的 AppCrash

Javascript:在树中查找元素的所有父项

F#遍历互递归树统计元素

algorithm - 全组合树算法

c - 程序不断循环

arrays - char 指针数组的大小