fork_bomb.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. #include <signal.h>
  8. #include <sys/time.h>
  9. int firstpid;
  10. int secondpid;
  11. #define NTRIES 1000
  12. #define TEST_TIMES 32
  13. #define DO_BENCH 1
  14. int count = 0;
  15. void sighand1 (int signum)
  16. {
  17. count++;
  18. #ifndef DO_BENCH
  19. printf("%d receive a SIGUSR (count = %d)\n",getpid(), count);
  20. #endif
  21. kill(secondpid, SIGUSR1);
  22. }
  23. void sighand2 (int signum)
  24. {
  25. count++;
  26. #ifndef DO_BENCH
  27. printf("%d receive a SIGUSR (count = %d)\n",getpid(), count);
  28. #endif
  29. kill(firstpid, SIGUSR1);
  30. }
  31. int main(int argc, char ** argv)
  32. {
  33. int times = TEST_TIMES;
  34. for (int i = 0 ; i < times; i++) {
  35. int pipes[2];
  36. pipe(pipes);
  37. firstpid = fork();
  38. if (firstpid < 0) {
  39. printf("fork failed\n");
  40. return -1;
  41. }
  42. if (firstpid == 0) {
  43. close(pipes[1]);
  44. signal(SIGUSR1, sighand1);
  45. read(pipes[0], &secondpid, sizeof(int));
  46. #ifndef DO_BENCH
  47. printf("%d killing %d\n",getpid(), secondpid);
  48. #endif
  49. struct timeval start_time;
  50. gettimeofday(&start_time, NULL);
  51. kill(secondpid, SIGUSR1);
  52. while (count < NTRIES - 1)
  53. sleep(1);
  54. struct timeval finish_time;
  55. gettimeofday(&finish_time, NULL);
  56. printf("%d time spent: %lu microsecond\n", getpid(),
  57. (finish_time.tv_sec * 1000000L + finish_time.tv_usec)
  58. - (start_time.tv_sec * 1000000L + start_time.tv_usec));
  59. exit(0);
  60. }
  61. close(pipes[0]);
  62. secondpid = fork();
  63. if (secondpid < 0) {
  64. printf("fork failed\n");
  65. return -1;
  66. }
  67. if (secondpid == 0) {
  68. signal(SIGUSR1, sighand2);
  69. secondpid = getpid();
  70. write(pipes[1], &secondpid, sizeof(int));
  71. struct timeval start_time;
  72. gettimeofday(&start_time, NULL);
  73. while (count < NTRIES)
  74. sleep(1);
  75. struct timeval finish_time;
  76. gettimeofday(&finish_time, NULL);
  77. printf("%d time spent: %lu microsecond\n",getpid(),
  78. (finish_time.tv_sec * 1000000L + finish_time.tv_usec)
  79. - (start_time.tv_sec * 1000000L + start_time.tv_usec));
  80. exit(0);
  81. }
  82. }
  83. return 0;
  84. }