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;
}
john = fork( ); //fork a new process, we have 2 now.
if (john == 0) {// child process go in the if statement
fork( ); //child process fork to 2 processes
fork( ); //2 processes continue to fork,so we have 2 more.
fork( ); //4 processes continue to fork, so we have 4 more.
}
//up to here, the child process of the first fork is now 8 processes
//adding the first parent process, that is 9 in total.
Remember that on the fork();fork();fork();
, both the parent and the child hit the next fork.
main
|
|\ john = fork()
| \
| \
| |\ fork()
| | \-----\
| |\ |\ fork()
| | \ | \
| | \ | \
| | \ | \
| |\ |\ |\ |\ fork()
| | | | | | | | |
1 2 3 4 5 6 7 8 9
P1 forks, creating P2. P1 has john = <NOT ZERO>
, and P2 has john = 0
. Therefore P2 executes the if
. 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.
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.