main.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/stat.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <unistd.h>
  9. #define BUFFER_SIZE 256
  10. #define PIPE_NAME "/bin/fifo"
  11. int main()
  12. {
  13. pid_t pid;
  14. int pipe_fd;
  15. char buffer[BUFFER_SIZE];
  16. int bytes_read;
  17. int status;
  18. // 创建命名管道
  19. mkfifo(PIPE_NAME, 0666);
  20. // 创建子进程
  21. pid = fork();
  22. if (pid < 0)
  23. {
  24. fprintf(stderr, "Fork failed\n");
  25. return 1;
  26. }
  27. else if (pid == 0)
  28. {
  29. // 子进程
  30. // 打开管道以供读取
  31. pipe_fd = open(PIPE_NAME, O_RDONLY);
  32. // 从管道中读取数据
  33. bytes_read = read(pipe_fd, buffer, BUFFER_SIZE);
  34. if (bytes_read > 0)
  35. {
  36. printf("Child process received message: %s\n", buffer);
  37. }
  38. // 关闭管道文件描述符
  39. close(pipe_fd);
  40. // 删除命名管道
  41. unlink(PIPE_NAME);
  42. exit(0);
  43. }
  44. else
  45. {
  46. // 父进程
  47. // 打开管道以供写入
  48. pipe_fd = open(PIPE_NAME, O_WRONLY);
  49. // 向管道写入数据
  50. const char *message = "Hello from parent process";
  51. write(pipe_fd, message, strlen(message) + 1);
  52. // 关闭管道文件描述符
  53. close(pipe_fd);
  54. // 等待子进程结束
  55. waitpid(pid, &status, 0);
  56. if (WIFEXITED(status))
  57. {
  58. printf("Child process exited with status: %d\n", WEXITSTATUS(status));
  59. }
  60. }
  61. return 0;
  62. }