Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Exercise 2.2 using namespace std; #include <iostream> #include <unistd.h> main()

ID: 662583 • Letter: E

Question

Exercise 2.2

using namespace std; #include <iostream> #include <unistd.h> main() {    int retval;    retval = fork();     if (retval > 0)    {       cout << "Inside parent" << retval << endl;    }    else    {       sleep(5);       cout << "Inside child" << retval << endl;    }    cout << "Who am I" << getpid() << endl; while(1); }

Questions:

1) First, please run this 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) What is the difference between this and previous exercise? Compare two codes and justify your answer. In particular, what is the effect of presence or absence of the sleep(5)?

Explanation / Answer

In a simple way:

p = fork();
if (0 == p)
{
// We're the child process
}
else if (p > 0)
{
// We're the parent process
}
else
{
// We're the parent process, but child couldn't be created
}