fork(2) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <signal.h>
  4. #include <errno.h>
  5. #include <assert.h>
  6.  
  7. #include <unistd.h>
  8. #include <sched.h>
  9.  
  10. pid_t parent_pid;
  11.  
  12. void sigquit_handler (int sig) {
  13. assert(sig == SIGQUIT);
  14. pid_t self = getpid();
  15. if (parent_pid != self) _exit(0);
  16. }
  17.  
  18. int main ()
  19. {
  20. int i;
  21.  
  22. signal(SIGQUIT, sigquit_handler);
  23. parent_pid = getpid();
  24.  
  25. puts("launching children");
  26. fflush(stdout);
  27. for (i = 0; i < 5; ++i) {
  28. pid_t p = fork();
  29. switch (p) {
  30. case 0:
  31. printf("child running: %d\n", (int)getpid());
  32. fflush(stdout);
  33. sleep(100);
  34. abort();
  35. case -1:
  36. perror("fork");
  37. abort();
  38. default:
  39. break;
  40. }
  41. }
  42.  
  43. puts("sleeping 1 second");
  44. sleep(1);
  45.  
  46. puts("killing children");
  47. kill(-parent_pid, SIGQUIT);
  48. for (i = 0; i < 5; ++i) {
  49. int status;
  50. for (;;) {
  51. pid_t child = wait(&status);
  52. if (child > 0 && WIFEXITED(status) && WEXITSTATUS(status) == 0) {
  53. printf("child %d succesully quit\n", (int)child);
  54. } else if (child < 0 && errno == EINTR) {
  55. continue;
  56. } else {
  57. perror("wait");
  58. abort();
  59. }
  60. break;
  61. }
  62. }
  63.  
  64. puts("sleeping 5 seconds");
  65. sleep(5);
  66.  
  67. puts("done");
  68. return 0;
  69. }
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
launching children
child running: 31307
child running: 31308
child running: 31306
child running: 31305
child running: 31304
sleeping 1 second
killing children
child 31304 succesully quit
child 31305 succesully quit
child 31306 succesully quit
child 31307 succesully quit
child 31308 succesully quit
sleeping 5 seconds
done