tags:

views:

99

answers:

2

I am trying to figure out the output for a block of C code using fork() and I am having some problems understanding why it comes out the way it does. I understand that when using fork() it starts another instance of the program in parallel and that the child instance will return 0. Could someone explain step by step the output to the block of code below? Thank you. EDIT: I FORGOT TO ADD THE EXIT(1) AFTER THE FOR LOOP. MY APOLOGIES.

main() { int status, i;
         for (i=0; i<2; ++i){
             printf("At the top of pass %d\n", i);
             if (fork() == 0){
                printf("this is a child, i=%d\n", i);
             } else {
                 wait(&status);
                 printf("This is a parent, i=%d\n", i);
               }
          }
          exit(1);
}
A: 

This code can be tricky to explain. The reason why is that the first child does not exit and will itself call fork. Try modifying the code to include the process id on each print line such as:

printf("At the top of pass %d in pid %u\n", i, getpid());

Then notice how the child becomes the parent...

R Samuel Klatchko
+1  A: 

What happens on the first loop is that the first process forks. In one, fork() returns 0 and in the other it returns the pid of the child process So you'll get one that prints out "this is a child" and one that prints out "this is a parent". Both of those processes continue through the loop, incremement i to 1 and fork() again. Now you've got four processes: two children and two parents. All four processes will increment i to 2 and break out of the loop.

If you increased the loop termination condition to i<3 then the next time around the loop all four processes will execute fork() and you'd have eight processes in total. If there was no limit in the loop, you'd have a fork bomb where you'd just exponentially create more and more processes each loop until the system runs out of resources.

Dean Harding
Hrm. I think I count 3 and 6 respectively. Maybe I need to actually run the code myself...
Ignacio Vazquez-Abrams
One minor nit. *Both of those processes continue through the loop* is not quite correct; since the parent has called wait, only the child continues through the loop; the parent of that particular fork won't continue until the child exits.
R Samuel Klatchko
Ah, 7 on the second run. But I see why.
Ignacio Vazquez-Abrams
@R Samuel Klatchko: Oh, you're right, I didn't notice the `wait()`.
Dean Harding
Seephor