Advanced On the fork () function is used

Create a review mid-term exam today and found two fork () procedure, all within a for loop, very suitable for learning fork () use of multiple sub-processes

 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\n", getpid(), x);
 8 
 9     }
10 }
11 return 0;
12 }
13     

Program 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   }

Program 2

Wherein the execution result of the program of FIG. 1 is as follows:

 

 Until the beginning of a very puzzled ??? read this article: https://blog.csdn.net/jason314/article/details/5640969#commentBox , I was myself clear how the matter

Schematic:

 

 

 

The process of Figure 2 after the execution of the program should look like this:

 

 

 

Guess you like

Origin www.cnblogs.com/mrlonely2018/p/11802948.html