...
int main(void)
{
int i;
for(i=0;i<2;i++){
switch(fork()){
case 0:
sleep(1);
break;
default:
sleep(1);
}
}
while(i--) wait(NULL);
return 0;
}
Hi. I’m trying to understand processes and forks.
I’m not sure how many processes does this code snippet create.
1 for the main program, then the main program duplicates itself (a child process is created), and then the child duplicates itself (2 children and the main process).
So those are 3 processes.
Am I correct or am I missing something?
There is a
forloop in the main thread (t1) that will callfork()twice (-> t1.1, t1.2). The first forked-thread (t1.1) has one more iteration, so it creates another (-> t1.1.1). Neither t1.2 nor t1.1.1 has any more iterations left, so no more threads forked.This leaves us with 4 threads altoghether