CppLearner
CppLearner

Reputation: 17040

Fork repeats twice?

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

int main()
{
    int a = 1, b = 1;
    int rval, pid;

    pid = fork();
    switch(pid)
    {
        case -1:
            printf("I am bad.\n");

        case 0:
            printf("I am in child.\n");
            rval = a + b;
            printf("leaving child.\n");
        default:
            wait();
            printf("I am back to parent.\n");
            //wait();
            printf("%d \n", rval);
            printf("leaving parent.\n");
    }
    return 0;
}

I was expecting child statements first, then parents. But there shouldn't be any reptition. Instead,

>> ./demo
I am in child.
leaving child.
I am back to parent.
2 
leaving parent.
I am back to parent.
134513584 
leaving parent.

Parent is repeated twice. Why is that? Furthermore, how did parent get 2 from the child? Child's has its own virtual memory for a and b so how did we transfer that result to parent? I am confused.


Further investigation When I insert return 0 into the case 0, it will not repeat. It looks like the switch statement continues. Did I miss something about switch statement?

Upvotes: 1

Views: 919

Answers (3)

Anshul garg
Anshul garg

Reputation: 233

As fork returns two pid's one to parent process and other to child process, for parent it returns > 0 pid and for child returns 0 as pid. Hence case for 0 gets executed but there is no break so default is also executed because in absence of break statement switch case falls through....

Upvotes: 0

pb2q
pb2q

Reputation: 59617

You have no break statements in your cases, and so each case falls through to the next. The child, with pid == 0, will execute both the 0 and default case blocks.

Upvotes: 6

Marco Leogrande
Marco Leogrande

Reputation: 8468

In C, switch statements fall through cases by default; you have to put a break; (or return) statement at the end of each case, otherwise, e.g., the child will execute both the child and the parent code.

Upvotes: 9

Related Questions