如何制作“二进制过程树”?

时间:2013-05-14 18:07:30

标签: c process fork

我有很多创建过程。每个儿子都要创造两个儿子。我使用递归解决方案,它可以工作,但创建的进程数量不是我想要的。

这就是我的尝试:

void generate_kid(int g, int res){
  pid_t kid1, kid2;
  int status1, status2;
  if( res > 0 ){
    if( kid1 = fork() ){
      if( res > 0){
        if( kid2 = fork() ){
        }
        else {
          printf("I am %d, my father is %d\n",getpid(),getppid());
          generate_kid(g,res/2-1);
        }
      }
    }
    else {
      printf("I am %d, my father is %d\n",getpid(),getppid());
      generate_kid(g,res/2-1);
    }
  }
  waitpid(kid1,&status1,0);
  waitpid(kid2,&status2,0);
}

1 个答案:

答案 0 :(得分:1)

试试这个:

void generate_kid(int res){
  pid_t kid1, kid2;
  int status1, status2;

  if( res > 0 ){
    if ((kid1 = fork())  == 0) {
      // child
      printf("I am %d, my father is %d\n",getpid(),getppid());
      // generate half remaining rounded up for odd processes
      generate_kid((res-1)/2);
    }
    else if (kid1 > 0) {
      // parent - create second child
      if( res > 1){
        if ((kid2 = fork()) == 0) {
          // child 2
          printf("I am %d, my father is %d\n",getpid(),getppid());
          // generate half remaining processes
          generate_kid((res-2)/2);
        }
        else if (kid2 > 0){
          // parent 2
          waitpid(kid2,&status2,0);
        }
      }
      waitpid(kid1,&status1,0);
    }
  }
}