Reputation: 17
I start programming in C and I cannot understand why these two programs take 3 and 6 seconds respectively to run. If anyone can help me thanks :)
Program 1 :
int main(){
int i;
for(i=1;i<=3;i++)
{
if(fork()==0)
{
sleep(i);
exit(0);
}
}
for(i=1;i<=3;i++)
{
wait(NULL);
}
return 0;
}
Program 2 :
int main(){
int i;
for(i=1;i<=3;i++)
{
if(fork()==0)
{
sleep(i);
exit(0);
}
wait(NULL);
}
return 0;
}
Upvotes: 0
Views: 103
Reputation: 151
So, here is some things to understand first:
Fork:
Wait(NULL):
So for the first problem:
The max sleep time is 3 seconds (i= 3). Since the processes don't wait on each other (except for when they are about to terminate), the whole process only takes 3 seconds (the sleeps happen concurrently).
Try understanding the second on your own, feel free to ask questions.
Upvotes: 2
Reputation: 924
3 and 6 seconds are the correct amount of time each should run.
The difference between the two is that one spawns all three processes and then waits on all of them simultaneously, while the other spawns one process and then waits before spawning the other. This is the effect of moving the wait(NULL)
inside or outside the loop.
Program 1:
t parent child 1 child 2 child 3
0 fork()x3 sleep sleep sleep
1 wait sleep sleep
2 wait sleep
3 done
Program 2
t parent child 1 child 2 child 3
0 fork();wait sleep
1 fork();wait sleep
2 wait sleep
3 fork();wait sleep
4 wait sleep
5 wait sleep
Upvotes: 2
Reputation: 780663
In the first program, the loop that calls fork()
doesn't wait for wach child to exit before it continues and creates the next child. So all 3 children are started at about the same time.
The second loop then waits for all of them to exit. It will complete when the third child exits, which is 3 seconds after the program started.
The second program calls wait()
inside the loop that creates the children. So it doesn't start child 2 until after child 1 has exited. So the total time is the sum of all the sleep times, rather than just the largest time.
It's much easier to see the difference when you indent the code properly.
Upvotes: 2