多级单亲单子进程树?

时间:2018-08-21 22:58:02

标签: linux unix process fork

所以我想写一个程序来创建多级子进程。与单亲和独生子女。

示例:Parent-> child1-> child2-> child3。像那样。 See image here

但是问题是我想从终端输入要创建多少个子进程(单父-单个子进程)。

所以我该如何将该 Nested if 语句修改为某种循环,以便它将按我的意愿创建子进程。

所以我的代码在这里

$insert->execute();

此处输出:

#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main() {

int a, b;

    {
        if(fork() == 0)
        {
        printf("child my pid is %d ppid is %d\n",getpid(),getppid());
            if(fork()== 0)
            {
             printf("child my pid is %d ppid is %d\n",getpid(),getppid());

               if(fork()== 0)
             {
             printf("child my pid is %d ppid is %d\n",getpid(),getppid());
                }
            }

        }
        else
        printf("father my pid is %d ppid is %d\n",getpid(),getppid());

    }
    for(int i=0;i<3;i++)
    wait(NULL);

return 0;
}

1 个答案:

答案 0 :(得分:0)

只需循环一下:

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

int main(int argc, char *argv[]) 
{
    assert(argc == 2);
    int num = atoi(argv[1]);
    for (int i = 0; i < num; ++i) {
         int child;
         switch ((child = fork())) { 
         case 0: 
            printf("child my pid is %d ppid is %d\n", getpid(), getppid());
            break;
         case -1:
            fprintf(stderr, "fork failed\n");
            break;
         default:
            printf("father my pid is %d ppid is %d and i just created %d\n",getpid(), getppid(), child);
            i = num; // break of loop
            break;
         }
    }
    wait(NULL);

    return 0;
}

@edit:

循环中断在错误的位置。现在,流程将按预期创建流程树:
使用gcc编译代码并运行:

$ ./a.out 5
father my pid is 21893 ppid is 21640 and i just created 21894
child my pid is 21894 ppid is 21893
father my pid is 21894 ppid is 21893 and i just created 21895
child my pid is 21895 ppid is 21894
father my pid is 21895 ppid is 21894 and i just created 21896
child my pid is 21896 ppid is 21895
father my pid is 21896 ppid is 21895 and i just created 21897
child my pid is 21897 ppid is 21896
father my pid is 21897 ppid is 21896 and i just created 21898
child my pid is 21898 ppid is 21897

程序:

  • 开头为pid 21893
  • 用pid 21894创建孩子
  • 孩子21894创建孩子21895
  • 孩子21895创建孩子21896
  • 孩子21896创建孩子21897
  • 孩子21907创建孩子21898