Can anyone please explain how this C code works? How many processes will be spawned after its completion?
int main(void)
{
int i;
for(i=1; i<=42; i++)
{
fork();
}
return 0;
}
Can anyone please explain how this C code works? How many processes will be spawned after its completion?
int main(void)
{
int i;
for(i=1; i<=42; i++)
{
fork();
}
return 0;
}
At each iteration of the for loop, fork is called exactly once. For each call of fork a new process is created; how many processes are spawned at the end depends on the length of the loop.
If the loop had length 1, only one new process would be created, for a total of 2 processes.
If the loop had length 2, at the first iteration a new process would be created; each process would then spawn another one at the next iteration, for a total of 3 calls to fork and 4 total processes.
As you might suppose, at each iteration the number of processes doubles; if n is the length of the loop, we're saying that the total number of processes would be f(n) = 2^n (with 2^n - 1 processes spawned). Let's prove it's true by induction. We have already seen that the formula holds for n=1 and n=2. Let's suppose it's valid for n and prove it for n+1.
If the lenght is n+1, at the first iteration a new process is spawned, for a total of 2 processes each still having n iterations to do, which means (by inductive assumption) that each process will spawn 2^n - 1 processes, which means that a total of 2^(n+1) - 2 processes will be spawned in the last n iterations; we already had 2 processes, which means that the total created processes (counting the main one) would be 2^(n+1) - 2 + 2 = 2^(n+1).
In conclusion, for a loop of lenght n we have 2^n - 1 calls to fork, which means that in your case we have 2^42 - 1 new processes spawned by the main one and its descendants.
Use this program to get the answer:
#include<stdio.h>
#include<math.h>
int main()
{
float sum=0;
int i;
for(i=1;i<=42;i++)
{
sum = sum + pow(2,i);
printf("fork call:%d, processes:%1.f\n",i,sum);
}
return 0;
}
//When fork call is 42 the processes will be 8796093022208