#include #include #include #include using namespace std; int main() { bool done{false}; srand(time(nullptr)); int count{1}; pid_t forkId{fork()}; switch(forkId) { case -1: perror("Error, Fork"); exit(1); case 0: cout << "Child created " << getpid() << endl; while (not done) { usleep(10000); float exitChance = rand() / static_cast(RAND_MAX); count++; if (exitChance > .9999) { done = true; } if (count % 1000 == 0) { cout << "\tChild here, I got 1000 iterations in" << endl; } usleep(300); } cout << "\t\t HA HA I got done before you killed me" << endl; exit(4); default: int status; pid_t childPid; while (not done) { int flags { WUNTRACED | WCONTINUED | WNOHANG}; childPid = waitpid(forkId, &status, flags); if (childPid != 0) { if (WIFEXITED(status)) { cout << "exited, status=" << WEXITSTATUS(status) << endl; done = true; } else if (WIFSIGNALED(status)) { cout << "killed by signal " << WTERMSIG(status) << endl; done = true; } else if (WIFSTOPPED(status)) { cout << "stopped by signal " << WSTOPSIG(status) << endl; } else if (WIFCONTINUED(status)) { cout << "continued" << endl; } } else { usleep(1000000); cout << "Parent finished work " << endl; } } break; } return 0; }