In: Computer Science
Read programs and find out their outputs. Please provide process tree with our answer to get full points.
(a)
#include <unistd.h> #include <stdlib.h> #include
<stdio.h>
int main()
{ for(i=0;i<3;i++)
if(fork()>0) printf(“A\n”); }
(b)
#include <unistd.h> #include <stdlib.h> #include
<stdio.h>
int gVar=0;
int main() {
int lVar=0;
int *p;
p=(int *)malloc(sizeof(int));
int pid=fork(); if(pid>0){
gVar=1;
lVar=1;
*p=1;
printf("%d, %d, %d\n", gVar, lVar, *p);
}else{
gVar=2;
lVar=2;
*p=2;
printf("%d, %d, %d\n", gVar, lVar, *p);
} }
(c) Read the following code and answer the questions below:
#include <unistd.h> #include <stdio.h>
main() {
int i;
for(i=0;i<3;i++) if(i%2==1)
fork(); else{
fork();
fork(); }
}
(1) How many processes are created by the OS when it runs the following program?
(2) Suppose your answer to (1) is n, and let us denote the n processes as P1, P2, ..., Pn, please describe the parent-child relations among the processes.
Answer to the question no 1:
Since the total number of processes will be 2^3 -1 = 7. So A will be printed 7 times.
Ans to question no. 2: when fork() will be called, there will be 2 processes parent and child. pid of the parent will be greater than 0 and the pid of the child process will be 0 so both if and else condition will be executed in a sequential manner. the output of second code will be 1,1,1 newline 2,2,2.
Ans to question no. 3: Total number of processes will be 10. Since the process P1, P2, P3 are created as same as question 1 in level 1 at i=0,1,2. because at i=0 and 2 fork of the forked process id introduces so at i=1 the number of processes will be doubled. In figure 1 the processes are 3. So at i =0, the processes will become 2*3 = 6. Since at i=2 no other process can be forked. An overall increase in the number of processes will be 3 fro i =0 due to else statement from question no 1.