fork_bomb.c 2.7 KB

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