This is the example I was given and I was asked how many processes are created.
c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void){
int pid = (int)fork();
pid = fork();
pid = fork();
printf("%d\n", pid);
if (pid == 0){
fork();
}
fork();
return 0
}
Initially I see 5 forks so 2^5 - 1 = 31 processes. However it quickly became apparent that was not the case as the if (pid == 0){ fork(); } throws me off.
I modified the code to get some sort of count:
c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int count = 1;
int main(void){
int pid = (int)fork();
pid = fork();
pid = fork();
if (pid == 0){
printf("2 ");
fork();
}
fork();
printf("1 ");
return 0;
}
Result:
1 1 1 1 2 1 1 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 1 2 1 2 1 2 1
That is 24 1's and 8 2's Using this information I would assume 24-1 = 23 processes were created 8 of which by the if loop but I simply can't explain it and if I should minus 1 in the first place. I would greatly appreciate some input on this thanks.