pid_kill.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. #include <signal.h>
  8. #include <sys/time.h>
  9. int firstpid;
  10. int secondpid;
  11. #define NTRIES 10000
  12. int count = 0;
  13. void sighand1 (int signum, siginfo_t * sinfo, void * ucontext)
  14. {
  15. count++;
  16. printf("firstpid receive a SIGUSR from %d (count = %d)\n",
  17. sinfo->si_pid, count);
  18. kill(secondpid, SIGUSR1);
  19. }
  20. void sighand2 (int signum, siginfo_t * sinfo, void * ucontext)
  21. {
  22. count++;
  23. printf("secondpid receive a SIGUSR from %d (count = %d)\n",
  24. sinfo->si_pid, count);
  25. kill(firstpid, SIGUSR1);
  26. }
  27. int main(int argc, char ** argv)
  28. {
  29. int pipes[2];
  30. pipe(pipes);
  31. firstpid = fork();
  32. if (firstpid < 0) {
  33. printf("fork failed\n");
  34. return -1;
  35. }
  36. if (firstpid == 0) {
  37. close(pipes[1]);
  38. struct timeval start_time;
  39. gettimeofday(&start_time, NULL);
  40. signal(SIGUSR1, (void *) sighand1);
  41. read(pipes[0], &secondpid, sizeof(int));
  42. kill(secondpid, SIGUSR1);
  43. while (count < NTRIES - 1)
  44. sleep(1);
  45. struct timeval finish_time;
  46. gettimeofday(&finish_time, NULL);
  47. printf("time spent: %lu microsecond\n",
  48. (finish_time.tv_sec * 1000000L + finish_time.tv_usec)
  49. - (start_time.tv_sec * 1000000L + start_time.tv_usec));
  50. return 0;
  51. }
  52. close(pipes[0]);
  53. secondpid = fork();
  54. if (secondpid < 0) {
  55. printf("fork failed\n");
  56. return -1;
  57. }
  58. if (secondpid == 0) {
  59. struct timeval start_time;
  60. gettimeofday(&start_time, NULL);
  61. signal(SIGUSR1, (void *) sighand2);
  62. secondpid = getpid();
  63. write(pipes[1], &secondpid, sizeof(int));
  64. while (count < NTRIES)
  65. sleep(1);
  66. struct timeval finish_time;
  67. gettimeofday(&finish_time, NULL);
  68. printf("time spent: %lu microsecond\n",
  69. (finish_time.tv_sec * 1000000L + finish_time.tv_usec)
  70. - (start_time.tv_sec * 1000000L + start_time.tv_usec));
  71. return 0;
  72. }
  73. waitpid(-1, NULL, 0);
  74. waitpid(-1, NULL, 0);
  75. return 0;
  76. }