Exercise 2.1 Questions: 1) First, please run the following program and give a br
ID: 662582 • Letter: E
Question
Exercise 2.1
Questions:
1) First, please run the following program and give a brief explanation of what happens and why? If you have a question about what would happen if we change the program as [your idea], do so. Post the revised program, its output and its explanation.
2) How many different outputs are expected for this example to be printed out on the screen? Please justify your answer. Please note that multiple runs of the program might not generate all logically possible solutions.
using namespace std; #include <iostream> #include <unistd.h> main() { int retval; retval = fork(); if (retval > 0) { cout << "Inside parent" << endl; } else { // sleep(5); cout << "Inside child" << endl; } cout << "Who am I" << endl; while(1); }
Explanation / Answer
1.
The program(given in question 2) creates a child process, and prints 2 lines of text each for parent and child.
2.
4 lines of text, 2 for child and 2 for parent. After a child is created, there are 2 processes running for the same program, 1 parent and 1 child. So, after the fork() call, the program checks whether the current process is parent or child(by its pid returned). if it is parent, 'Inside parent' is printed, then 'Who am I' is printed. After that, the other process running for the same program, which is child process, 'Inside child' and 'Who am I' is printed. So, final output is:
Inside parent
Who am I
Inside child
Who am I
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.