#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, const char * argv[]) {
for(int i = 0; i < 2; i++){
if(fork() == 0){
fork();
printf("c");
}
else{
fork();
printf("p");
}
}
}
I want to count how many times p and c will be printed respectively, here is my work.
Draw a process tree for i == 0:
P
/ \
C1 P
/ \ / \
C2 C1 C3 P
I call this a subtree. In one subtree, P gives p, C3 gives c, C1 gives p, C2 gives c. In the second iteration, each leaf will hold a subtree like this, so in the end we will have 5 subtree in total. Since one subtree gives 2 p, 2 c, 5 subtrees will gives 10 p, 10 c. But this is wrong.
What went wrong?
Update: I found I made a mistake, here is the correction: P gives p, C3 gives p, C1 gives c, C2 gives c.