Question: We can make a parent process waiting for its child to finish before continuing by using wait : #include #include pid_t wait (int *stat_loc); The
We can make a parent process waiting for its child to finish before continuing by using wait:
| #include #include pid_t wait (int *stat_loc); |
The status information is written to stat_loc.
Try the following program:
| //test_wait.cpp #include #include #include #include #include #include using namespace std; int main() { pid_t pid; //process id char *message; int n; int exit_code; cout << "fork program starting "; pid = fork(); switch (pid) { case -1: cout << "Fork failure! "; return 1; case 0: message = "This is the child "; n = 5; exit_code = 9; break; default: message = "This is the parent "; n = 3; exit_code = 0; break; } for (int i = 0; i < n; ++i) { cout << message; sleep (1); } //waiting for child to finish if (pid != 0) { //parent int stat_val; pid_t child_pid; child_pid = wait (&stat_val); //wait for child cout << "Child finished: PID = " << child_pid << endl; if (WIFEXITED (stat_val)) cout << "child exited with code " << WEXITSTATUS (stat_val) << endl; else cout << "child terminated abnormally!" << endl; } exit (exit_code); } |
Requirement:
Run the program and explain what you have seen on the screen. Modify the program so that the child process creates another child and wait for it. The grandchild prints out the IDs of itself, its parent and grandparent.
Can someone help me please?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
