T
thrillseekersforever
The questions(A&B) are to fine no# of process running from the below
codes. However, I couldn't decipher the solution. Will someone please
throw some light on this? Thanks a lot!!
A]
void main() {
....
pid1 = fork();
if (pid1) pid2 = fork();
.....
}
Solution:
In the first two lines, the parent process forks a child (pid1), then
the same parent (the process holding a nonzero pid1) forks another
child (pid2). Therefore, the effect of the first two lines was to
multiply the number of processes by 3.
B]
void main() {
....
pid1 = fork(); pid2 = fork();
if (pid1 || pid2) execvp(...);
pid3 = fork(); pid4 = fork();
if (pid3 || pid4) execvp(...);
pid5 = fork(); pid6 = fork();
if (pid5 || pid6) execvp(...);
}
In the first line, the two unconditional forks bring the number of
processes to 4. Then, in the second line, 3 out of these 4 processes
are exec'd toward another program: they are the processes that were
playing the parent role either during fork1 or during fork2. So,
conversely, only the fork2-child of the fork1-child will continue
executing this code (i.e., the process with both pid1 and pid2 zero).
Therefore, the next two lines apply only to that remaining process,
which also creates 3 more processes, of which only one remains (the
fork4-child of the fork3-child). Then, the last two lines repeat
exactly the same pattern.
In conclusion, the total number of processes that were created
(whether exec'd or not) is:
1 + 3 + 3 + 3 = 10.
codes. However, I couldn't decipher the solution. Will someone please
throw some light on this? Thanks a lot!!
A]
void main() {
....
pid1 = fork();
if (pid1) pid2 = fork();
.....
}
Solution:
In the first two lines, the parent process forks a child (pid1), then
the same parent (the process holding a nonzero pid1) forks another
child (pid2). Therefore, the effect of the first two lines was to
multiply the number of processes by 3.
B]
void main() {
....
pid1 = fork(); pid2 = fork();
if (pid1 || pid2) execvp(...);
pid3 = fork(); pid4 = fork();
if (pid3 || pid4) execvp(...);
pid5 = fork(); pid6 = fork();
if (pid5 || pid6) execvp(...);
}
In the first line, the two unconditional forks bring the number of
processes to 4. Then, in the second line, 3 out of these 4 processes
are exec'd toward another program: they are the processes that were
playing the parent role either during fork1 or during fork2. So,
conversely, only the fork2-child of the fork1-child will continue
executing this code (i.e., the process with both pid1 and pid2 zero).
Therefore, the next two lines apply only to that remaining process,
which also creates 3 more processes, of which only one remains (the
fork4-child of the fork3-child). Then, the last two lines repeat
exactly the same pattern.
In conclusion, the total number of processes that were created
(whether exec'd or not) is:
1 + 3 + 3 + 3 = 10.