main.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #include <errno.h>
  2. #include <signal.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/wait.h>
  7. #include <unistd.h>
  8. #define BUFFER_SIZE 1024
  9. #define MSG "Hello from parent!\n"
  10. static int handled_signal = 0;
  11. // 子进程的信号处理函数
  12. void child_signal_handler(int sig) {
  13. printf("Child received signal %d\n", sig);
  14. handled_signal = 1;
  15. }
  16. // 父进程的信号处理函数
  17. void parent_signal_handler(int sig) {
  18. printf("Parent received signal %d\n", sig);
  19. }
  20. int main() {
  21. int pipefd[2];
  22. pid_t pid;
  23. char buffer[BUFFER_SIZE];
  24. // 创建管道
  25. if (pipe(pipefd) == -1) {
  26. perror("pipe");
  27. exit(EXIT_FAILURE);
  28. }
  29. // 创建子进程
  30. pid = fork();
  31. if (pid == -1) {
  32. perror("fork");
  33. exit(EXIT_FAILURE);
  34. }
  35. if (pid == 0) {
  36. // 子进程
  37. close(pipefd[1]); // 关闭写端
  38. // 设置子进程的信号处理函数
  39. signal(SIGUSR1, child_signal_handler);
  40. printf("Child: Waiting for data...\n");
  41. // 尝试从管道中读取数据
  42. ssize_t bytes_read = read(pipefd[0], buffer, BUFFER_SIZE - 1);
  43. if (bytes_read == -1) {
  44. printf("[FAILED]: Child: read error, errno=%d\n", errno);
  45. exit(EXIT_FAILURE);
  46. } else if (bytes_read == 0) {
  47. printf("Child: End of file\n");
  48. }
  49. if (bytes_read != sizeof(MSG) - 1) {
  50. printf("[FAILED]: Child: read error: got %ld bytes, expected %ld\n",
  51. bytes_read, sizeof(MSG) - 1);
  52. } else {
  53. printf("[PASS]: Child: read success: got %ld bytes, expected %ld\n",
  54. bytes_read, sizeof(MSG) - 1);
  55. }
  56. buffer[bytes_read] = '\0';
  57. printf("Child: Received message: %s", buffer);
  58. close(pipefd[0]);
  59. if (!handled_signal)
  60. printf("[FAILED]: Parent: child did not handle signal\n");
  61. else
  62. printf("[PASS]: Parent: child handled signal\n");
  63. exit(EXIT_SUCCESS);
  64. } else {
  65. // 父进程
  66. close(pipefd[0]); // 关闭读端
  67. // 设置父进程的信号处理函数
  68. signal(SIGCHLD, parent_signal_handler);
  69. // 发送信号给子进程,中断它的读操作
  70. sleep(1); // 确保子进程已经开始读取
  71. // printf("Parent: Sending SIGCHLD to child...\n");
  72. // kill(pid, SIGCHLD);
  73. printf("Parent: Sending SIGUSR1 to child...\n");
  74. kill(pid, SIGUSR1);
  75. sleep(1); // 确保子进程已经处理了信号
  76. write(pipefd[1], MSG, strlen(MSG));
  77. printf("Parent: Sent message: %s", MSG);
  78. // 等待子进程结束
  79. waitpid(pid, NULL, 0);
  80. printf("Parent: Child process finished.\n");
  81. close(pipefd[1]);
  82. exit(EXIT_SUCCESS);
  83. }
  84. }