Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created September 16, 2020 06:51
Show Gist options
  • Save ProfAvery/4504a3ce6264a0e58719cf99aa109fc1 to your computer and use it in GitHub Desktop.
Save ProfAvery/4504a3ce6264a0e58719cf99aa109fc1 to your computer and use it in GitHub Desktop.
In-class Exercise: Parent and Child Processes
#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