Answer:
Here is the program:
#include <stdio.h> //to use input output functions
#include <unistd.h>
//provides access to the POSIX OS API
int main() {
//start of main function
int x; //declare an int type variable x
x = 100; // sets the value of x to 100
int r = fork(); //calls fork() method to create a new process. r is used to store the value returned by fork()
if(r<0){ //if fork() returns -1 this means no child process is created
fprintf(stderr, "Error");}
//prints the error message using standard error stream
else if (r == 0) { //if fork returns 0 this means child process is created
printf("This is child process\n"); //prints this message
x = 150; //changes value of x to 150
printf("Value of x in child process: %d\n", x); } //prints the new value of x in child process
else {
printf("This is parent process\n"); //if r>0
x = 200; //changes value of x to 200
printf("Value of x in parent process: %d\n", x); } } //prints the new value of x in parent process
Explanation:
The program is well explained in the comments added to each line of the code. The answers to the rest of the questions are as follows:
What value is the variable in the child process?
The variable x is set to 150 in child process. So the printf() statement displays 150 on the screen.
What happens to the variable when both the child and parent change the value of x?
fork() creates a copy of parent process. The child and parent processes have their own private address space. Therefore none of the both processes cannot interfere in each other's memory. The both maintain their own copy of variables. So, when parent process prints the value 200 and child process prints the value 150.
In order to see which is the final value of x, lets write a statement outside all of the if else statements:
printf("Final value of x: %d\n", x);
This line is displayed after the value of parent class i.e. 200 is printed on the screen and it shows:
Final value of x: 200
Note this is the value of x in parent process
However the same line displayed after the value of child class i.e. 150 is printed on the screen and it shows:
Final value of x: 150
The screenshot of the program along with the output is attached.