Search code examples
for-loopforktrace

How to trace fork() inside for loop?


int i;
for(i=1; i<=3; i++)
{
    fork();
    printf("H\n");
}
Result 14 times H

1)When I try binary tree technique or 2(power)N. I end up with 8 outputs. 2)Also when I take out curly brackets, I end up with 8.

What are the differences?


Solution

  • i=1
    fork -----------------------
    "H" (printed)              "H" (printed)
    i=2 (next loop)            i=2
    fork----------             fork----------       
    "H"          "H"           "H"           "H"    
    i=3          i=3           i=3           i=3
    fork----     fork----      fork----      fork----     
    "H"    "H"   "H"    "H"    "H"    "H"    "H"    "H"
    

    2+4+8 = 14 prints of "H"

    with out the curly brackets you only get the printf after the loop, that's the bottom row, 8 prints of "H"