Linux 管道通信详解
一、进程间通信基础
进程间通信(IPC)的核心在于不同进程之间如何交换信息。常见需求包括数据传输、资源共享、事件通知以及进程控制。
在 Linux 系统中,主要的 IPC 方式包括管道、System V IPC 和 POSIX IPC。由于进程具有独立性,实现通信的前提是它们必须能访问同一份资源。
二、管道机制
1. 什么是管道
管道是类 Unix 系统中最古老的 IPC 方式之一。简单来说,它将一个进程的输出连接到另一个进程的输入,形成一条数据流通道。

关键特性:
- 单向通信:只能单工传输,双向通信需创建两个管道。
- 分类:分为匿名管道和命名管道。
2. 匿名管道
匿名管道(pipe)主要用于有亲缘关系的进程之间(如父子进程)。它本质上是内核管理的一块内存区域,通过一对文件描述符(fd[0] 读端,fd[1] 写端)来操作。随着进程退出,管道自动销毁。
核心 API
使用 pipe() 系统调用创建管道。成功返回 0,失败返回 -1。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int pipefd[2] = {0};
// 创建管道,pipefd[0] 为读端,pipefd[1] 为写端
if (pipe(pipefd) != 0) {
perror("pipe error");
exit(1);
}
(, pipefd[], pipefd[]);
id = fork();
(id == ) {
close(pipefd[]);
* msg = ;
cnt = ;
outbuffer[];
(cnt) {
(outbuffer, (outbuffer), , msg, cnt--);
write(pipefd[], outbuffer, (outbuffer));
sleep();
}
close(pipefd[]);
();
} {
close(pipefd[]);
inbuffer[];
() {
inbuffer[] = ;
n = read(pipefd[], inbuffer, (inbuffer) - );
(n > ) {
inbuffer[n] = ;
(, inbuffer);
} (n == ) {
();
close(pipefd[]);
;
} {
perror();
;
}
}
waitpid(id, , );
}
;
}


