How many processes are created by the program?
int main(){
int i;
for(i=0;i<4;i++)
fork();
return 0;
}
Answer:
The formula for this fork() related problem is
Total number of process created = Child processes + Parent process = (2^n) -1) + 1
where { (2n) -1 } = number of Child Process and 1 is for Parent Process.
Now here fork() is called 4 times. That means n = 4 . so put n=4 in the above formula we get the total number of processes created as 16.
Among which 15 = 2^n - 1 are child process. And 1 is the parent process.
so the answer is 16 here.
How many processes will create:
for ( i = 1; i<=3; i++ )
{
fork();
fork();
}
Answer:
Here we can see that a total of 6 times fork() will call, so the total number of the process will be 2^6 including the parent process, which is 64
#include <stdio.h>
#include <unistd.h>
int main() {
if(fork() && fork())
fork();
printf("Hello");
return 0;
}
Now, the compiler will execute the code, and when the if statement comes, the first fork command will be executed, and a child process will be created, and both the process (child process and parent process) will run parallelly, as you can see in the below diagram.
Now the child process C1 will print Hello
As you can see the AND operator is written after the first fork() so it will also get executed, so another child process from the parent process will get created. As you can see in the diagram below.
This C2 will also print Hello
Now then if the statement is completely executed, and now the fork() statement written inside the if statement will get executed. And again a child process of parent process will be created. As you can see in the diagram below.
This child process and parent process will print Hello
Here, in total fork is done 3 times, and in total 4 times Hello will be printed.