#include #include #include #include #include #include using namespace std; const int NAP_TIME = 5; int myid; bool loop = true; void sigHandler(int sig) { loop = false; cout << "CHILD: " << myid << " or " << getpid() << " got hit with a " << sig << " and is now exiting " << endl; return; } int main() { vector children; int nprocs = 5; int i; pid_t child; int wstatus; int coin; if (signal(SIGHUP, sigHandler)== SIG_ERR) { perror("signal"); } srand(time(NULL)); coin = rand()%nprocs + 1; cout << "PARENT: Child with id " << coin << " will exit " << endl; myid = 0; for(i = 1; i <= nprocs and myid == 0; i++) { child = fork(); if (child == 0) { myid = i; } else { children.push_back(child); } } cout << getpid() << " is process number " << myid << endl; if (myid > 0) { if (coin == myid) { // randomly selected child to exit after a while sleep(NAP_TIME); cout << endl; cout << "CHILD: id " << myid << " won the coin toss and will now exit " << endl; return 0; } else { // other childern while (loop) ; cout << "Exit by id " << myid << endl; } } else { // parent child = wait(&wstatus); cout << endl; cout << "PARENT: Child with pid " << child << " exited " << endl; cout << "PARENT: Forcing an exit on all other children " << endl; for(i=0;i