edited by
1,358 views
11 votes
11 votes
find total no of processes i am getting 29 as answer as all will be child process except one parent process plz explain how answer is 24 here i am very confused in such question by drawing diagram

#include<stdio.h>

#include<stdlib.h>

int main(void)

{

pid_t  pid = fork();

pid = fork();

pid = fork();

if(pid == 0)

{

fork();

}

fork();

return 0;

}
edited by

3 Answers

Best answer
4 votes
4 votes

Child process = 23 ( count the number of C's in above image) , Root = 1 , this is parent process.

Total number of process created = 23 +1 = 24 

selected by
2 votes
2 votes

It's not really complicated! Just read through it!

The fork call creates a new process every time that it's called.  0 is given to (child) process and the process id of the child (not zero) is given to original (parent) process.

pid_t pid = fork();  // fork #1
pid = fork();        // fork #2
pid = fork();        // fork #3
if (pid == 0)
{
  fork();            // fork #4
}
fork();              // fork #5
  1. Fork #1 creates an new processes. You now have (2) processes.
  2. Fork #2 is executed by the above (2) processes, creating (2) more processes, for a total of (4).
  3. Fork #3 is executed by above (4) processes, creating (4) more processes, for a total of(8). Half of those have pid==0 (childs)and oher half have pid != 0
  4. Fork #4 is executed by half of the processes created by above fork #3 (so,(4) enters if). This creates (4) more additional processes. So (4) + (4) --> due to if condition and the other half that didn't enter if is (4) processes. Totally You now have (12) processes.
  5. Fork #5 is executed by all (12) of the remaining processes, creating (12) more processes; you now have twenty-four (12)+(12) --> (24)
0 votes
0 votes

You can ask from this explanation and correct me if am wrong 


Answer:

Related questions

1 votes
1 votes
2 answers
1
Warrior asked Nov 10, 2018
1,358 views
0 votes
0 votes
1 answer
2
abhinowKatore asked Jan 13, 2023
1,472 views
int doWork(){ fork(); fork(); printf("Hello world!\n");}int main() { doWork(); printf("Hello world!\n"); exit(0);}
1 votes
1 votes
2 answers
4
junaid ahmad asked Jan 1, 2019
1,496 views
int main(void) { int var1=100; int pid; if(pid==fork()) var1=200; fork(); printf("%d",var1); return 0; }what could be the output ?a)100 100 200 200b)200 200 200 200c)none...