打印多个叉子的语句

时间:2017-03-23 01:48:12

标签: c fork

int counter = 0;
int main()
{
   int i;
   for (i = 0; i < 2; i ++){
      fork();
      counter ++;
      printf("counter = %d\n", counter);
}
  printf("counter = %d\n", counter);
  return 0;
}

绘制fork进程时,counter只获得7个printfs。

为什么(应该)打印counter 10次?

这就是我的视觉效果:

                      ____1____2__
                     |
           _____fork |____1____2__
          |     __________1____2___
          |fork|
          |    |
main__fork|____|_____________2_____  

The numbers 1 and 2 represent `counter` printed by `printf`. Could anyone explain this (visually would be great) ?

1 个答案:

答案 0 :(得分:1)

您忘记了每个进程在结束前都会打印一段额外的时间。

因此,例如,第一个进程打印“counter = 0”,“counter = 1”,“counter = 2”,然后退出循环,在终止之前打印一个额外的“counter = 2”。

如果您更改每个printf以包含PID和printf,那么代码将更容易理解。

  循环中

,counter = 1,pid = 11755
  在循环中,counter = 2,pid = 11755
  退出循环,计数器= 2,pid = 11755
  在循环中,counter = 1,pid = 11756
  在循环中,counter = 2,pid = 11756
  退出循环,计数器= 2,pid = 11756
  in loop,counter = 2,pid = 11758
  退出循环,计数器= 2,pid = 11758
  在循环中,counter = 2,pid = 11757
  退出循环,计数器= 2,pid = 11757