Linux进程通信:匿名管道详解
匿名管道(Anonymous Pipe)是Linux中一种经典的进程间通信(IPC)机制,主要用于具有亲缘关系的进程间数据传输。其本质是由内核管理的单向数据流,遵循先进先出(FIFO)原则,仅支持单向通信。
匿名管道的核心特性
匿名管道通过系统调用pipe()创建,返回两个文件描述符:fd[0]用于读取,fd[1]用于写入。数据从写入端流向读取端,默认大小为64KB(可通过fcntl()调整)。
典型应用场景包括父子进程通信或兄弟进程协同。由于没有持久化标识,匿名管道仅适用于存在共同祖先的进程。
匿名管道的创建与使用
以下代码展示父子进程通过匿名管道通信的完整流程:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int pipefd[2];
char buffer[1024];
if (pipe(pipefd) == -1) {
perror("pipe creation failed");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
close(pipefd[1]); // 关闭写端
ssize_t count = read(pipefd[0], buffer, sizeof(buffer));
if (count == -1) {
perror("read failed");
exit(EXIT_FAILURE);
}
printf("Child received: %.*s\n", (int)count, buffer);
close(pipefd[0]);
} else { // 父进程
close(pipefd[0]); // 关闭读端
const char* msg = "Hello from parent";
write(pipefd[1],
1284

被折叠的 条评论
为什么被折叠?



