sigchld.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <errno.h>
  4. #include <stdio.h>
  5. #include <sys/signal.h>
  6. #include <sys/wait.h>
  7. #include <unistd.h>
  8. void test_handler(int signo)
  9. {
  10. write(1, "caught SIGCHLD\n", 15);
  11. return;
  12. }
  13. int main(void)
  14. {
  15. pid_t mypid;
  16. struct sigaction siga;
  17. static sigset_t sigset;
  18. /* Set up sighandling */
  19. sigfillset(&sigset);
  20. siga.sa_handler = test_handler;
  21. siga.sa_mask = sigset;
  22. siga.sa_flags = 0;
  23. if (sigaction(SIGCHLD, &siga, (struct sigaction *)NULL) != 0) {
  24. fprintf(stderr, "sigaction choked: %s!", strerror(errno));
  25. exit(EXIT_FAILURE);
  26. }
  27. /* Setup a child process to exercise the sig handling for us */
  28. mypid = getpid();
  29. if (fork() == 0) {
  30. int i;
  31. for (i=0; i < 3; i++) {
  32. sleep(2);
  33. kill(mypid, SIGCHLD);
  34. }
  35. _exit(EXIT_SUCCESS);
  36. }
  37. /* Wait for signals */
  38. write(1, "waiting for a SIGCHLD\n",22);
  39. for(;;) {
  40. sleep(10);
  41. if (waitpid(-1, NULL, WNOHANG | WUNTRACED) > 0)
  42. break;
  43. write(1, "after sleep\n", 12);
  44. }
  45. printf("Bye-bye! All done!\n");
  46. return 0;
  47. }