// Fork.cpp // Working with UNIX processes: To compile and run: // g++ fork.cpp -o fork // chmod u+x fork // ./fork // ./fork > fork.out // #include // defines pid_t #include // defines fork #include // defines cout, cin #include // defines exit() #include // defines wait() using namespace std; class Process { public: Process() {} int laugh(int sleep_time,char* text); private: }; int Process::laugh(int sleep_time, char* text) { // Get process ID pid_t identification = getpid(); // Print text 5000 times in rows of 10 for (int i=0; i<500000; i++) { if (sleep_time > 0) sleep (sleep_time); cout << text << " "; if (i%10==0) cout << endl; } // Print that process is done - with its ID cout << "Completed: " << identification << endl; exit(0); // do not return } int main() { Process child; int stat; // returns a status from the child here int sleep_time; char Ha[] = "Ha!"; char Ho[] = "Ho!"; char He[] = "He!"; // get time to sleep cerr << "sleep_time (-1 to +3): "; cin >> sleep_time; // Create children if (fork() == 0) // child process child.laugh(sleep_time,Ha); if (fork() == 0) // child process child.laugh(sleep_time,Ho); if (fork() == 0) // child process child.laugh(sleep_time,He); // Have parent pause to wait for all children to complete before terminating //wait(&stat); //wait(&stat); //wait(&stat); // sleep(10); // Sleep 10 seconds if wait() does not work cout << "All done" << endl; }