Search code examples
cfork

Why does hello world print twice only and why is a's largest value 2


#include <stdio.h>
#include <unistd.h>

int main() {
    int a=0;
    int rc=fork();
    a++;
    if(rc=0)
    {
        rc=fork();

        a++;
    }
    else
    {
       a++;
    }
    printf("Hello World");
    printf("%d",a);

    return 0;
}

Solution

  • Why does hello world print twice only and why is a's largest value 2

    To answer your question (after correcting your (rc = 0) vs. (rc == 0) issue), it may help to diagram what is happening in your code. For example:

        parent
          |
          a = 1
          if (rc == 0)
          +--------------- child 1
          |                   |
          else                +--------------- child 2
            a++               a++              a++
          a = 2               a = 2            a = 2
          Hello World2        Hello World2     Hello World2
    

    In the parent process, you fork and then increment a with a++ before your test of if (rc == 0) to give direction to the child process. The original parent sees a++ again due to the else and "Hello World2" is the result.

    In the first-child, you fork again, but the child-1 (as parent) and child-2 both increment a++; before dropping out of the conditional with "Hello World2" the result for both.

    It appears you were attempting something similar to:

    #include <stdio.h>
    #include <unistd.h>
    
    int main (void) {
    
        int a = 1,
            rc = fork();
    
        if (rc == 0) {
            a++;
            rc = fork();
    
            if (rc == 0)
                a++;
        }
    
        printf ("Hello World %d\n", a);
    }
    

    Example Use/Output

    $ ./bin/forkcount
    Hello World 1
    Hello World 2
    Hello World 3
    

    Sometimes a pencil and paper is as helpful as a keyboard. Let me know if you have further questions.