test_mkfifo.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. pid_t pid;
  13. int pipe_fd;
  14. char buffer[BUFFER_SIZE];
  15. int bytes_read;
  16. int status;
  17. // 创建命名管道
  18. mkfifo(PIPE_NAME, 0666);
  19. // 创建子进程
  20. pid = fork();
  21. if (pid < 0) {
  22. fprintf(stderr, "Fork failed\n");
  23. return 1;
  24. } else if (pid == 0) {
  25. // 子进程
  26. // 打开管道以供读取
  27. pipe_fd = open(PIPE_NAME, O_RDONLY);
  28. // 从管道中读取数据
  29. bytes_read = read(pipe_fd, buffer, BUFFER_SIZE);
  30. if (bytes_read > 0) {
  31. printf("Child process received message: %s\n", buffer);
  32. }
  33. // 关闭管道文件描述符
  34. close(pipe_fd);
  35. // 删除命名管道
  36. unlink(PIPE_NAME);
  37. exit(0);
  38. } else {
  39. // 父进程
  40. // 打开管道以供写入
  41. pipe_fd = open(PIPE_NAME, O_WRONLY);
  42. // 向管道写入数据
  43. const char *message = "Hello from parent process";
  44. write(pipe_fd, message, strlen(message) + 1);
  45. // 关闭管道文件描述符
  46. close(pipe_fd);
  47. // 等待子进程结束
  48. waitpid(pid, &status, 0);
  49. if (WIFEXITED(status)) {
  50. printf("Child process exited with status: %d\n", WEXITSTATUS(status));
  51. }
  52. }
  53. return 0;
  54. }