Linux 进程通信——匿名管道
匿名管道(Anonymous Pipe)是Linux中一种简单的进程间通信(IPC)机制,主要用于具有亲缘关系的进程(如父子进程)之间的单向数据传输。其本质是一个内核缓冲区,通过文件描述符实现读写操作。匿名管道的数据遵循先进先出(FIFO)原则,且生命周期随进程结束而终止。
匿名管道的特点
- 单向通信:数据只能从一端写入,另一端读出。
- 亲缘关系限制:通常用于父子进程或兄弟进程间通信。
- 内存缓冲区:管道数据存储在内存中,无需磁盘文件。
- 阻塞与非阻塞:默认情况下,读写操作可能阻塞,可通过
fcntl设置为非阻塞模式。
创建匿名管道
匿名管道通过pipe()系统调用创建,函数原型如下:
#include <unistd.h>
int pipe(int fd[2]);
fd[0]为读端文件描述符,fd[1]为写端。- 成功返回0,失败返回-1并设置
errno。
父子进程通信示例
以下代码展示父子进程通过匿名管道传递数据:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int fd[2];
pid_t pid;
char buf[1024];
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid > 0) { // 父进程
close(fd[0]); // 关闭读端
const char *msg = "Hello from parent!";
write(fd[1], msg, strlen(msg) + 1);
close(fd[1]);
} else { // 子进程
close(fd[1]); // 关闭写端
read(fd[0], buf, sizeof(buf));
1443

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



