fork_bomb.c 2.3 KB

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