Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* To enable core dumps: ulimit -c <size> */
- /* To inquire on size: ulimit -c */
- /* To process a dump: gdb waitpid core */
- #include <stdio.h> /* perror, ... */
- #include <stdlib.h> /* exit, ... */
- #include <string.h> /* strsignal, ... */
- #include <sys/types.h> /* pid_t, ... */
- #include <sys/wait.h> /* waitpid, ... */
- #include <unistd.h> /* fork, ... */
- #define CHILD 0
- #define FORK_ERROR -1
- typedef int (*child)(void);
- static void fork_with_child(child function);
- static void wait_for_child(pid_t pid);
- static int normal_child();
- static int abort_child();
- static int divide_by_zero();
- static int raise_sigsegv();
- static const int CHILD_RC = 42;
- int main(int argc, char *argv[]) {
- fork_with_child(normal_child);
- fork_with_child(abort_child);
- fork_with_child(divide_by_zero);
- fork_with_child(raise_sigsegv);
- printf("\n");
- return EXIT_SUCCESS;
- }
- static void fork_with_child(child function) {
- pid_t child_pid;
- switch ( (child_pid = fork()) ) {
- case FORK_ERROR:
- perror("fork");
- exit(1);
- case CHILD:
- exit(function());
- default:
- wait_for_child(child_pid);
- break;
- }
- }
- static void wait_for_child(pid_t child_pid) {
- int child_status;
- waitpid(child_pid, &child_status, 0);
- if ( WIFEXITED(child_status) ) {
- printf("child exited with rc %d\n", WEXITSTATUS(child_status));
- }
- else if ( WIFSIGNALED(child_status) ) {
- printf("child exited with signal %s\n", strsignal(WTERMSIG(child_status)));
- if ( WCOREDUMP(child_status) ) {
- printf("core dump produced\n");
- }
- }
- }
- static int normal_child() {
- printf("\nnormal_child returning %d\n", CHILD_RC);
- return CHILD_RC;
- }
- static int abort_child() {
- printf("\nabort_child aborting\n");
- abort();
- return EXIT_SUCCESS; /* Should not reach this */
- }
- static int divide_by_zero() {
- int i = 1;
- int j = 0;
- printf("\ndivide_by_zero dividing by zero\n");
- fflush(stdout);
- i /= j;
- return EXIT_SUCCESS; /* Should not reach this */
- }
- static int raise_sigsegv() {
- printf("\nraise_sigsegv raising SIGSEGV\n");
- raise(SIGSEGV);
- return EXIT_SUCCESS; /* Should not reach this */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement