论fork()函数的进阶使用

今天复习期中考试,发现两个fork()的程序,都在for循环内,非常适合用来学习fork()的使用,多个子进程的创建

 1 int main (){
 2     int i, x, f; 
 3     x = 1;
 4     for (i = 0; i < 3; i++) { f = fork ();
 5         if (f == 0) {
 6         x = x * 2;
 7         printf ("pid %d : %d
", getpid(), x);
 8 
 9     }
10 }
11 return 0;
12 }
13     

程序1

 1   int  main ( void ){
 2         int  i, naptime ;
 3         for( i= 0 ; i< 4 ; i++)  if( fork ())  break ;
 4 
 5       srand ( getpid ());
 6       sleep ( naptime  =  rand ()% 4 );
 7 
 8        printf (" Mon  nom  est   <% c>,  "
 9                          "j’ ai  dormi  % d  secondes  n ",’A ’+ i, naptime );
10 
11      exit( EXIT_ SUCCESS );
12   }

程序2

其中,程序1的执行结果如下图:

 一开始非常疑惑···直到看了这篇文章:https://blog.csdn.net/jason314/article/details/5640969#commentBox,我才自己搞清楚是怎么回事

原理图:

而程序2执行后的进程图应该是这样的:

原文地址:https://www.cnblogs.com/mrlonely2018/p/11802948.html