Question

So my output for the code below includes printing D twice, and I can't seem to understand why. It'll be great if someone could explain it to me.

int main() {
    int r = fork();
    printf("B\n");
    int t = fork();
    printf("C\n");
    if(r == 0) {
        printf("D\n");
    } else if (r > 0 && t == 0){
        printf("E\n");
    }
    printf("F\n");
    return 0;
}

Thanks.

Was it helpful?

Solution

Let's use naming convention to easily describe how the code runs. Let's call the parent that executes X=fork() Xparent and the forked child Xchild. Parents end up with X > 0 and child with X==0.

You have a parent that executes r=fork() and t=fork() making it an Rparent and a Tparent.

We now know that Rchild will have r==0 and Tchild will have t==0.

However, the older child, Rchild, executes t=fork() making it a Tparent and forking a Tchild.

The Tchild forked by Rchild will have r==0, memories from parent and child are cloned.

Hence you end up with Rchild having r==0 and its child having r==0. Two processes printing D.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top