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