#include #include #include #include #include #include #include #include using namespace std; int main () { vector procs; vector ::iterator pos; int i; pid_t parentPID; pid_t pid; int status; parentPID = getpid(); int options = 0; // serve up a heaping helping of processes. for(i=0;i<10;i++) { if (parentPID == getpid()) { pid = fork(); if (pid != 0) { procs.push_back(pid); } } } if (pid == 0) { int sleepTime; cout << "\tChild here " << endl; srand(getpid()); sleepTime = rand() % 20 + 5 ; cout << "\tChild " << getpid() << " sleeping for " << sleepTime << endl; sleep (sleepTime); cout << "\tChild " << getpid() << " exiting " << endl; return 0; } else { cout << "Parent here with " << procs.size() << " children " << endl; while (procs.size() > 0) { pid_t child; pid = procs[procs.size()-1]; //options = WNOHANG; cout << "Parent waiting on " << pid << endl; child = waitpid(pid,&status, options); if (child != 0) { cout << "Parent, child " << child << " just exited " << endl; pos = find(procs.begin(), procs.end(),child); if (pos != procs.end()) { procs.erase(pos); } } cout << "Parent still has " << procs.size() << " children " << endl; } } return 0; }