#include #include #include #include #include #include void parent_work(); void child_work(); int main(int argc, char *argv[]) { int pid; int start = 0; srand(time(NULL)); // initialize random number generator pid = fork(); if (pid > 0) // Parent case { parent_work(); wait(NULL); // Print before shell prompt appears printf("After call to wait() in parent\n"); } else if (pid == 0) // Child case child_work(); else // If unable to fork a process exit(1); printf("\n"); } void parent_work() { int i, j; int r = rand() % 10; // Decide how much "work" to do for (i = 0; i < 10; ++i) { for (j = 0; j < 7000000 * r; ++j) // Do the "work" ; printf("i = %d, Parent\n", i); } } void child_work() { int i, j; int r = rand() % 10; // Decide how much "work" to do for (i = 0; i < 10; ++i) { for (j = 0; j < 10000000 * r; ++j) // Do the "work" ; printf("i = %d, Child\n", i); } } /* Example output: i = 0, Parent i = 0, Child i = 1, Parent i = 1, Child i = 2, Parent i = 3, Parent i = 2, Child i = 4, Parent i = 3, Child i = 5, Parent i = 6, Parent i = 4, Child i = 7, Parent i = 5, Child i = 8, Parent i = 9, Parent i = 6, Child i = 7, Child i = 8, Child i = 9, Child After call to wait() in parent */