fork() 函数如何工作?

how the fork() function works?

有人可以解释这段代码吗?

int main ( ){          
   int i=0 ;
   while (fork() !=0 && i<2)
      i=i+1;
   printf(" this is the process %d and ends with i=%d \n", getpid(), i);
   return 0;
}

据我了解,一个进程父有3个children! 但是根据这个执行输出,我不确定我是否理解了 fork 函数:

[root@www Desktop]# ./prog1
 this is the process 8025 and ends with i=2 
[root@www Desktop]#  this is the process 8027 and ends with i=1 
 this is the process 8028 and ends with i=2 
 this is the process 8026 and ends with i=0 

谢谢!

记住 fork() 分叉你的进程,导致两个 more-or-less 相同的进程,每个进程的区别是 return 对于 child,fork() 的值是 0, child 的 pid 用于 parent.

你的 while 循环只迭代 parent 个进程(它结束 child 个进程,因为在这些进程中 fork() 的 return 值为 0)。所以第一次通过 (i==0),child 进程失败,打印它的 pid,然后退出。 parent 仍然存在。

parent 递增 i,再次分叉,child (i==1) 落空,打印其 pid 并退出。所以这是一个 i==0 的出口和一个 i==1 的出口。

parent 递增 i,再次分叉,但 i 现在是 2,因此 parent 和 child 进程的 while 循环退出。两者都以 i==2 退出。所以总共是一个 i==0 出口,一个 i==1 出口和两个 i==2 出口。

需要牢记的其他几点:

  • 进程不保证是顺序的,因此输出可能是 out-of-(预期)-顺序(如您的示例所示)

  • 优化编译器也可能会扰乱排序。使用 -O0 编译可能会使输出(序列)更符合您的预期。

    $ gcc -w -O0 forktest.c && ./a.out
    this is the process 5028 and ends with i=0
    this is the process 5029 and ends with i=1
    this is the process 5030 and ends with i=2
    this is the process 5027 and ends with i=2