pid_kill.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 10000
  11. int count = 0;
  12. void sighand1(int signum, siginfo_t* sinfo, void* ucontext) {
  13. count++;
  14. printf("firstpid receive a SIGUSR from %d (count = %d)\n", sinfo->si_pid, count);
  15. kill(secondpid, SIGUSR1);
  16. }
  17. void sighand2(int signum, siginfo_t* sinfo, void* ucontext) {
  18. count++;
  19. printf("secondpid receive a SIGUSR from %d (count = %d)\n", sinfo->si_pid, count);
  20. kill(firstpid, SIGUSR1);
  21. }
  22. int main(int argc, char** argv) {
  23. int pipes[2];
  24. if (pipe(pipes) < 0) {
  25. perror("pipe failed");
  26. return 1;
  27. }
  28. firstpid = fork();
  29. if (firstpid < 0) {
  30. printf("fork failed\n");
  31. return -1;
  32. }
  33. if (firstpid == 0) {
  34. close(pipes[1]);
  35. struct timeval start_time;
  36. gettimeofday(&start_time, NULL);
  37. signal(SIGUSR1, (void*)sighand1);
  38. if (read(pipes[0], &secondpid, sizeof(int)) != sizeof(int)) {
  39. perror("read failed");
  40. return 1;
  41. }
  42. kill(secondpid, SIGUSR1);
  43. while (count < NTRIES - 1) {
  44. sleep(1);
  45. }
  46. struct timeval finish_time;
  47. gettimeofday(&finish_time, NULL);
  48. printf("time spent: %lu microsecond\n",
  49. (finish_time.tv_sec * 1000000L + finish_time.tv_usec) -
  50. (start_time.tv_sec * 1000000L + start_time.tv_usec));
  51. return 0;
  52. }
  53. close(pipes[0]);
  54. secondpid = fork();
  55. if (secondpid < 0) {
  56. printf("fork failed\n");
  57. return -1;
  58. }
  59. if (secondpid == 0) {
  60. struct timeval start_time;
  61. gettimeofday(&start_time, NULL);
  62. signal(SIGUSR1, (void*)sighand2);
  63. secondpid = getpid();
  64. if (write(pipes[1], &secondpid, sizeof(int)) != sizeof(int)) {
  65. perror("write error");
  66. return 1;
  67. }
  68. while (count < NTRIES) {
  69. sleep(1);
  70. }
  71. struct timeval finish_time;
  72. gettimeofday(&finish_time, NULL);
  73. printf("time spent: %lu microsecond\n",
  74. (finish_time.tv_sec * 1000000L + finish_time.tv_usec) -
  75. (start_time.tv_sec * 1000000L + start_time.tv_usec));
  76. return 0;
  77. }
  78. waitpid(-1, NULL, 0);
  79. waitpid(-1, NULL, 0);
  80. return 0;
  81. }