Advertisement
gocha

Short SIGCHLD sample

May 7th, 2014
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. // Short SIGCHLD sample. For details, visit:
  2. // <https://www.ipa.go.jp/security/awareness/vendor/programmingv1/b07_04.html>
  3.  
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. #include <unistd.h>
  9. #include <signal.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13.  
  14. void setup_SIGCHLD(void);
  15. void catch_SIGCHLD(int signo);
  16.  
  17. int main(void)
  18. {
  19.   int i;
  20.  
  21.   puts("main start.");
  22.  
  23.   setup_SIGCHLD();
  24.  
  25.   for (i = 0; i < 3; i++)
  26.   {
  27.     pid_t child_pid = fork();
  28.  
  29.     if(child_pid == -1) {
  30.       puts("fork error.");
  31.     }
  32.     else if(child_pid == 0) {
  33.       sleep(1);
  34.       exit(0);
  35.     }
  36.  
  37.     printf("child %d spawned.\n", child_pid);
  38.     sleep(1);
  39.   }
  40.  
  41.   puts("Press Ctrl+C to exit.");
  42.   while(1) {
  43.     sleep(1);
  44.   }
  45. }
  46.  
  47. void setup_SIGCHLD(void)
  48. {
  49.   struct sigaction act;
  50.   memset(&act, 0, sizeof(act));
  51.   act.sa_handler = catch_SIGCHLD;
  52.   sigemptyset(&act.sa_mask);
  53.   act.sa_flags = SA_NOCLDSTOP | SA_RESTART;
  54.   sigaction(SIGCHLD, &act, NULL);
  55. }
  56.  
  57. void catch_SIGCHLD(int signo)
  58. {
  59.   pid_t child_pid = 0;
  60.   puts("SIGCHLD trapped.");
  61.  
  62. #if 1
  63.   do {
  64.     int child_ret;
  65.     child_pid = waitpid(-1, &child_ret, WNOHANG);
  66.     printf("waitpid => %d, %d\n", child_pid, child_ret);
  67.   } while(child_pid > 0);
  68. #endif
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement