Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following section of code: #include <stdio.h> #include <stdlib.h> m

ID: 3883472 • Letter: C

Question

Consider the following section of code:

#include <stdio.h>
#include <stdlib.h>
main()
{
int ret_val;
int i;

for (i=1; i<=4; i++)
{
ret_val = fork();
if (ret_val == 0) {
printf("In child. ");
exit(0);
}
}
printf("In parent. ");
}


Assume that the fork() system call is successful.

(a) How many processes will be created (including the parent), and what will be
printed when the code is executed?

(b) Draw a graph depicting the parent-child relationships; e.g. the process
model.

(c) What happens if the exit(0) system call is removed? Include the process
model in your explanation.

Explanation / Answer

#include<stdlib.h>
main()
{
int ret_val;
int i;
for (i=1; i<=4; i++)
{
    ret_val = fork();
    if (ret_val == 0) {
       printf("In child. ");
       exit(0);
    }
}
printf("In parent. ");
}

a) Parent has forked 4 times. So total number of processes is 5.The ouput will be
   In child
   In child
   In child
   In child
   In parent

b) The process mode graph is as follows

     P--->---->---->---->
         |    |    |    |
         |    |    |    |
         c1   c2   c3   c4    (All the child processes terminated.)

c) The process mode graph is as follows (exit(0) removed

     P--->---->---->---->
         |    |    |    |
         |    |    |    |
         c1   c2   c3   c4    (All the child will fork .the subsequent child keep on forking. It will be a never ending loop.)