// CS 450: Process example 2: fork, timed wait // version 2013-01-22 11:42 am // #include #include // fork #include // exit #include // global error number #include // wait // Prototype for child processes pid_t child(int child_nbr, int sleeptime); int main(int argc, char *argv[]) { pid_t pid_child1, pid_child2, exited_child; int i, child_nbr, status; // Child 1 should sleep 3 sec; child 2 7 sec // pid_child1 = child(1, 3); pid_child2 = child(2, 7); printf("This is the parent\n"); // Wait twice: Each time, wait for a // child and print out its nbr & status for (i = 0 ; i < 2 ; i++) { exited_child = wait(&status); child_nbr = (exited_child == pid_child1 ? 1 : 2); printf("Child %d pid %d exited with status %d\n", child_nbr, exited_child, status ); } return 0; } // Child prints its pid and sleeps for a number // of seconds // pid_t child(int child_nbr, int sleeptime) { pid_t pid = fork(); if (pid > 0) { // Parent returns return pid; } else if (pid == -1) { // Fork failed !? fprintf(stderr, "Fork %d failed with error %d\n", child_nbr, errno ); exit(1); } // We're the child process printf("Child %d, pid %d\n", child_nbr, getpid()); sleep(sleeptime); exit(0); } // Sample output // // This is the parent // Child 1, pid 2055 // Child 2, pid 2056 // Child 1 pid 2055 exited with status 0 // Child 2 pid 2056 exited with status 0