pid_kill.c 2.1 KB

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