假设每个fork成功执行,将创建多少个进程(包括父进程)

时间:2017-07-09 05:06:07

标签: operating-system fork

我相信这创造了5个过程;但是,我需要验证。这些问题经常让我感到困惑。谢谢您的帮助!

void forktest()
{
   printf("L0\n");
   if (fork() != 0) 
   { 
       printf("L1\n");
       if (fork() != 0)
       {
           printf("L2\n");
           fork();
       }
   }
   printf("Bye\n");
}

1 个答案:

答案 0 :(得分:0)

main
   |
   |
fork  --- (first child)
   |
   |
fork  --- (second child)
   |
   |
fork  --- (third child)
void forktest()
{
   printf("L0\n");
   if (fork() != 0) <----- first child, only parent goes inside the if
   { 
       printf("L1\n");
       if (fork() != 0) <------ second child, only parent goes inside the if
       {
           printf("L2\n"); 
           fork();       <------ third child
       }
   }
   printf("Bye\n");
}

即,由main创建的3个进程。