实现思路
- 使用
pipe
函数创建管道,该函数会创建一个包含两个文件描述符的数组,一个用于读(fd[0]
),一个用于写(fd[1]
)。
- 使用
fork
函数创建子进程。
- 在父进程中关闭读端文件描述符(
fd[0]
),使用写端文件描述符(fd[1]
)向管道写入字符串。
- 在子进程中关闭写端文件描述符(
fd[1]
),使用读端文件描述符(fd[0]
)从管道读取字符串并打印。
关键代码片段
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main() {
int pipe_fd[2];
if (pipe(pipe_fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) { // 子进程
close(pipe_fd[1]); // 关闭写端
char buffer[BUFFER_SIZE];
ssize_t bytes_read = read(pipe_fd[0], buffer, sizeof(buffer) - 1);
if (bytes_read == -1) {
perror("read");
exit(EXIT_FAILURE);
}
buffer[bytes_read] = '\0';
printf("子进程接收到: %s\n", buffer);
close(pipe_fd[0]); // 关闭读端
} else { // 父进程
close(pipe_fd[0]); // 关闭读端
const char *message = "Hello, child process!";
if (write(pipe_fd[1], message, strlen(message)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
close(pipe_fd[1]); // 关闭写端
wait(NULL); // 等待子进程结束
}
return 0;
}