///////////////////////////////////////// // Fork.cpp // This program forks children. It prints child process ids. // It works with global and local variables. ////////////////////////////////////////// // 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; int global=0; class Process { public: Process() {} int count(char text); private: int index; }; int Process::count(char text) { index=0; // Get process ID pid_t identification = getpid(); cout << "Started: " << identification << endl; // Print text 5000 times in rows of 10 for (int i=0; i<50000; i++) { cout << text << index++; if (i%10==0) cout << " g" << global++ << 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 // Create children if (fork() == 0) // child process child.count('a'); if (fork() == 0) // child process child.count('b'); if (fork() == 0) // child process child.count('c'); // 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; }