Advertisement
Guest User

Untitled

a guest
Dec 7th, 2013
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. /* To enable core dumps: ulimit -c <size> */
  2. /* To inquire on size: ulimit -c */
  3. /* To process a dump: gdb waitpid core */
  4.  
  5. #include <stdio.h> /* perror, ... */
  6. #include <stdlib.h> /* exit, ... */
  7. #include <string.h> /* strsignal, ... */
  8. #include <sys/types.h> /* pid_t, ... */
  9. #include <sys/wait.h> /* waitpid, ... */
  10. #include <unistd.h> /* fork, ... */
  11.  
  12. #define CHILD 0
  13. #define FORK_ERROR -1
  14.  
  15. typedef int (*child)(void);
  16.  
  17. static void fork_with_child(child function);
  18. static void wait_for_child(pid_t pid);
  19.  
  20. static int normal_child();
  21. static int abort_child();
  22. static int divide_by_zero();
  23. static int raise_sigsegv();
  24.  
  25. static const int CHILD_RC = 42;
  26.  
  27. int main(int argc, char *argv[]) {
  28.  
  29. fork_with_child(normal_child);
  30. fork_with_child(abort_child);
  31. fork_with_child(divide_by_zero);
  32. fork_with_child(raise_sigsegv);
  33.  
  34. printf("\n");
  35. return EXIT_SUCCESS;
  36. }
  37.  
  38. static void fork_with_child(child function) {
  39.  
  40. pid_t child_pid;
  41.  
  42. switch ( (child_pid = fork()) ) {
  43. case FORK_ERROR:
  44. perror("fork");
  45. exit(1);
  46. case CHILD:
  47. exit(function());
  48. default:
  49. wait_for_child(child_pid);
  50. break;
  51. }
  52. }
  53.  
  54. static void wait_for_child(pid_t child_pid) {
  55.  
  56. int child_status;
  57. waitpid(child_pid, &child_status, 0);
  58.  
  59. if ( WIFEXITED(child_status) ) {
  60. printf("child exited with rc %d\n", WEXITSTATUS(child_status));
  61. }
  62. else if ( WIFSIGNALED(child_status) ) {
  63. printf("child exited with signal %s\n", strsignal(WTERMSIG(child_status)));
  64. if ( WCOREDUMP(child_status) ) {
  65. printf("core dump produced\n");
  66. }
  67. }
  68. }
  69.  
  70. static int normal_child() {
  71. printf("\nnormal_child returning %d\n", CHILD_RC);
  72. return CHILD_RC;
  73. }
  74.  
  75. static int abort_child() {
  76. printf("\nabort_child aborting\n");
  77. abort();
  78. return EXIT_SUCCESS; /* Should not reach this */
  79. }
  80.  
  81. static int divide_by_zero() {
  82.  
  83. int i = 1;
  84. int j = 0;
  85.  
  86. printf("\ndivide_by_zero dividing by zero\n");
  87. fflush(stdout);
  88. i /= j;
  89.  
  90. return EXIT_SUCCESS; /* Should not reach this */
  91. }
  92.  
  93. static int raise_sigsegv() {
  94. printf("\nraise_sigsegv raising SIGSEGV\n");
  95. raise(SIGSEGV);
  96. return EXIT_SUCCESS; /* Should not reach this */
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement