fork_bomb.c 2.4 KB

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