Help with output generated by this C code using fork()

Posted by Seephor on Stack Overflow See other posts from Stack Overflow or by Seephor
Published on 2010-04-13T00:00:15Z Indexed on 2010/04/13 0:02 UTC
Read the original article Hit count: 221

Filed under:
|
|

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.

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

© Stack Overflow or respective owner

Related posts about c

    Related posts about fork