/* file: fork_wait.c Extends simple_fork2.c, to include proper use of waitpid () to collect termination status of terminated child processes, and the macros for extracting status information. To compile this program: gcc -o fork_wait fork_wait.c */ #define _XOPEN_SOURCE 500 #include #include #include #include #include #include #include #include #include #include #define SLEEP_TIME 1 extern void print_child_status (int status); int main(int argc, char *argv[]) { pid_t child, result; int status; if (argc !=1) { fprintf (stderr, "This program does not accept command-line arguments\n"); exit (-1); } /* create a child process */ child = fork(); if (child == -1) { /* call to fork failed */ perror ("fork failed"); exit (-1); } if (child != 0) { fprintf (stdout, "This is the parent process, with own pid %d\n", getpid()); /* try to suspend the child */ fprintf (stdout, "This is the parent process, sending SIGSTOP to child\n"); if (kill (child, SIGSTOP) == -1) { perror ("kill of child failed"); exit (-1); } /* sleep for a time */ sleep (SLEEP_TIME); /* see if the child has stopped */ fprintf (stdout, "This is the parent process, waiting for child\n"); result = waitpid (child, &status, WUNTRACED | WNOHANG); if (result == -1) { perror ("first waitpid failed"); exit (-1); } else if (result == 0) perror ("child process not stopped or terminated"); else print_child_status (status); /* allow the child to continue */ fprintf (stdout, "This is the parent process, sending SIGCONT to child\n"); kill (child, SIGCONT); /* wait for the child to terminate */ if (waitpid (child, &status, 0) == -1) { perror ("second waitpid failed"); exit (-1); } print_child_status (status); } else { fprintf (stdout, "This is the child process, with own xpid %d " "and parent pid %d, about to sleep for %d seconds\n", (int) getpid(), (int) getppid(), SLEEP_TIME * 2); /* sleep for a time */ sleep (SLEEP_TIME * 2); fprintf (stdout, "This is the child process, about to exit\n"); return 2; } return 0; } /* sample output: [cop4610@websrv forkexec]$ ./forkwait This is the parent process, with own pid 28026 This is the parent process, sending SIGSTOP to child This is the parent process, waiting for child Child killed by signal 112 This is the parent process, sending SIGCONT to child This is the child process, with own xpid 28027 and parent pid 28026, about to sleep for 2 seconds This is the child process, about to exit Child exited with status 2 */