I'm trying to figure out how many processes this program creates, including the initial parent process. The correct answer should be 9, but I don't understand why the answer is 9. How are these 9 processes created? Thanks in advance!
#include <stdio.h>
#include <unistd.h>
…
int main()
{
pid_t john;
john = fork( );
if (john == 0) {
fork( ); fork( ); fork( );
}
/* Consume resources of another process */
/* This does NOT create a new process. */
Consume( ); Consume( );
return 0;
}
P1 forks, creating P2. P1 has
john = <NOT ZERO>
, and P2 hasjohn = 0
. Therefore P2 executes theif
. It forks, creating P3. Now, P2 and P3 are at the second fork. So they fork, creating P4 and P5. Now P2, P3, P4 and P5 all have one fork left. They fork, creating P6, P7, P8 and P9. Total of nine processes spawned.fork
creates an exact copy of the program image of the calling process, except for the fact that it returns 0 to the child and a PID to the parent. And the child will be at the same place as the parent is after the fork.Remember that on the
fork();fork();fork();
, both the parent and the child hit the next fork.friend, I am learning process too. And I got something about function fork(). You know, fork will create a new child process, and it will get a copy of data, content, stack, heap and so on from parent process, and child process will get a copy of PCB from parent process as well. Program's running is controled by Program Counter which contains the program's instructions. PCB contains the information of program counter. Because of the same PCB between child and parent, child process will run the left instructions of Program Counter, so in parent process the code before fork will not be run in the child. In the if statement, when the first fork run, the child process will only run the second and third fork. you can use this to draw a process diagram to help you resolve this question.Like this.Sorry, I don't have encough reputation to post a images for you. Hope my words can help you.