#include #include // fork #include // for wait, waitpid #include // for nanosleep, sleep #include // for kill #include // perror using namespace std; void SleepChild(int sec) { int sleeptime; int exitStatus; cout << "\tHello from the child, I have pid " << getpid() << endl; sleeptime = sec; do { cout << "\tChild going to sleep for " << sleeptime << " sec" << endl; sleeptime = sleep(sleeptime); } while (sleeptime > 0); // generate a random exit status. exitStatus = 1+rand()%255; cout <<"\tChild is exiting with value " << exitStatus << endl; // why exit here, not a return? exit(exitStatus); } void WaitChild(pid_t childPID) { pid_t tmp; int status; cout << "Parent waiting " << endl; cout << endl; //tmp = wait(&status); tmp = waitpid(-1,&status,WCONTINUED|WUNTRACED); if (tmp != -1) { cout << "Wait returned " << tmp << " which should be " << childPID << endl; cout << "The status was " << status << endl; if (WIFEXITED(status)) { cout << "The exit status was " << WEXITSTATUS(status) << endl; } else if (WIFSIGNALED(status)) { cout << "Killed by signal " << WTERMSIG(status) << endl; } else if (WIFSTOPPED(status) ) { cout << "The process was stopped " << endl; } else if (WIFCONTINUED(status) ) { cout << "The process was continued " << endl; } cout << endl ; } else { perror("Wait or waitpid"); } return; } int main() { srand(time(nullptr)); pid_t childPID; cout << " The parent will wait before the child exits. " << endl; childPID = fork(); if (childPID == 0) { SleepChild(2); } WaitChild(childPID); cout << endl << endl; cout << "Try that again." << endl; cout << "This time the child will exit before the parent waits" << endl; childPID = fork(); if (childPID == 0) { SleepChild(1); } cout << "Parent sleeping for 2" << endl; sleep(2); cout << "Parent going to wait" << endl; cout << endl; WaitChild(childPID); cout << endl << endl; cout << "One more time" << endl; cout << "This time parent will send the child signals." << endl; childPID = fork(); if (childPID == 0) { SleepChild(10); } sleep(1); cout << endl; cout << "\t\tSending SIGSTOP (" << SIGSTOP << ")" << endl; cout << endl; kill(childPID, SIGSTOP); WaitChild(childPID); cout << endl; cout << "\t\tSending SIGCONT (" << SIGCONT << ")" << endl; cout << endl; kill(childPID, SIGCONT); WaitChild(childPID); cout << endl; cout << "\t\tSending SIGUSR1 (" << SIGUSR1 << ")" << endl; cout << endl; kill(childPID, SIGUSR1); WaitChild(childPID); return 0; }