#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?
In C, switch statements fall through cases by default; you have to put a
break;(orreturn) statement at the end of each case, otherwise, e.g., the child will execute both the child and the parent code.