Using the program shown in Figure 3.35, explain what the output will be at lines X and Y

Using the program shown in Figure 3.35, explain what the output will be at lines X and Y

Using the program shown in Figure 3.35, explain what the output will be at lines X and Y

Answer

The output would be

CHILD: 0 CHILD: -1 CHILD: -4 CHILD: -9 CHILD: -16 PARENT: 0 PARENT: 1 PARENT: 2 PARENT: 3 PARENT: 4

Explanation:

After the fork() call , the process creates a child process. fork() call returns the pid of the child process to the parent and a 0 to the child process.

Now, In the child process, since if(pid==0) is satisfied, the for loop executes and the values are printed as follows

nums[0] = 0; i = 0 hence CHILD : 0 is printed

nums[1] = 1; i = 1 hence CHILD : -1 is printed

nums[2] = 2; i = 2 hence CHILD : -4 is printed

nums[3] = 3; i = 3 hence CHILD : -9 is printed

nums[4] = 4; i = 4 hence CHILD : -16 is printed

Meanwhile, in the parent process, wait(NULL) is executed and hence, the parent process waits for the child process to finish and after the child process finishes , the parent's for loop executes and prints the values.

Hence, the output would be

CHILD: 0 CHILD: -1 CHILD: -4 CHILD: -9 CHILD: -16 PARENT: 0 PARENT: 1 PARENT: 2 PARENT: 3 PARENT: 4

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts