Created
September 16, 2020 06:51
-
-
Save ProfAvery/4504a3ce6264a0e58719cf99aa109fc1 to your computer and use it in GitHub Desktop.
In-class Exercise: Parent and Child Processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdlib> | |
#include <iostream> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
using std::cout; | |
using std::endl; | |
int main() | |
{ | |
auto first_child_fork_returned = fork(); | |
if (first_child_fork_returned == 0) { | |
cout << "I am the first child." << endl; | |
auto grandchild_fork_returned = fork(); | |
if (grandchild_fork_returned == 0) { | |
cout << "I am the grandchild." << endl; | |
} else { // grandchild_fork_returned > 0 | |
cout << "I am the first child and have started the grandchild." << endl; | |
wait(NULL); // for grandchild | |
} | |
} else { // first_child_fork_returned > 0 | |
cout << "I am the parent and have started the first child." << endl; | |
wait(NULL); // for first child | |
auto second_child_fork_returned = fork(); | |
if (second_child_fork_returned == 0) { | |
cout << "I am the second child." << endl; | |
} else { // second_child_fork_returned > 0 | |
cout << "I am the parent and have started the second child." << endl; | |
wait(NULL); // for second child | |
} | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment