In: Computer Science
a. What will be the output of LINE A in code “a” and output of
code “b”? Also write
reasons for the outputs.
a. #include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int value = 3;
int main()
{
pid_t pid;
pid = fork();
if (pid = = 0) {/* child process */}
value += 233;
return 0;
}
else if (pid > 0) {/* parent process */}
wait(NULL);
printf(“PARENT: value = %d”, value); /* LINE
A */
return 0;
} }
b.
#include <stdio.h>
#include <unistd.h>
int main()
{
/* fork a child process */
fork();
/* fork another child process */
fork();
/* fork another child process */
fork();
/* and fork another */
fork();
return 0;
}
Here is your solution if you have any doubts then you can write in the comment section.
Please give feedback.
Solution:
Important points:-
(1) fork() command creates a new process called the child process and this process runs concurrently with the process which creates it called parent process.
(2) fork() will return 0 to the child process and return process id(>0)to the parent process which called fork() and return a negative number if child creation is unsuccessful.
(3)Both the Child process and the Parent process run concurrently in the same program but OS allocates different states and data to the process it means if there is any variable (global, local) 's value is changed in any one process doesn't affect another process.
By considering the above point we will find the output of the above problem.
Solution 1:
Here pid=fork(), a new process is created according to point 1.
so for child process pid=0 and for parent process pid will be a positive number according to point 2.
Now both process runs concurrently and in the child process if(pid==0) condition will be true and its value is incremented by 233 and return 0, and in the parent process if(pid>0) condition will be true and it will print value which is 3 for parent process because variables assigned to child and parent process separately according to point 3.
So it will print PARENT: Value=3
Solution 2:
In this program, there are four fork() called so we will see the result after each fork().
We will consider only point 1 for this program.
In this program there is no print statement means it doesn't print anything but a total of 15 child process will be created and finally, there will be 16 processes including parent process.
I Explained each fork() in the diagram if you have any doubts then you can write in the comment section.
Thank You!