Safus09
Safus09

Reputation: 101

how the fork() function works?

can some one explain this code ?

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

what I have understand that a process father has 3 children ! but according to this execution output I am not sure that I have understood the fork function :

[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 

Thank You !

Upvotes: 1

Views: 140

Answers (1)

Patrick
Patrick

Reputation: 197

Remember fork() forks your process, resulting in two more-or-less identical processes, the difference in each is the return value of fork() is 0 for the child, and the child's pid for the parent.

Your while loop only iterates for the parent processes (it ends for the child processes since in those processes the return value of fork() is 0). So the first time through (i==0), the child process falls through, prints its pid, and exits. The parent remains.

The parent increments i, forks again, the child (i==1) falls through, prints its pid and exits. So that's one exit with i==0 and one exit with i==1.

The parent increments i, forks again, but i is now 2, so the while loop exits for both parent and child processes. Both exit with i==2. So in total that's one exit i==0, one exit with i==1 and two exits with i==2.

A couple of other points to bear in mind:

  • processes are not guaranteed to be sequential, so the output may be out-of-(expected)-order (as it is in your example)

  • an optimising compiler may also mess with sequencing. Compiling with -O0 may make the output (sequence) more what you expect.

    $ 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
    

Upvotes: 3

Related Questions