pid_kill.c 2.1 KB

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