1.1 无名管道概述
管道(pipe)又称无名管道。 无名管道是一种特殊类型的文件,在应用层体现为两个打开的文件描述符。
任何一个进程在创建的时候,系统都会 给他分配4G的虚拟内存,分为3G的用户空间和1G 的内核空间,内核空间是所有进程公有的,无名管道就是创建在内核空间的,多个进程知道 同一个无名管道的空间,就可以利用他来进行通信
无名管道虽然是在内核空间创建的,但是会给当前用户进程两个文件描述符,一个负责执行 读操作,一个负责执行写操作
管道是最古老的UNIX IPC方式,其特点是:
1、半双工,数据在同一时刻只能在一个方向上流动。
2、数据只能从管道的一端写入,从另一端读出。
3、写入管道中的数据遵循先入先出的规则。
4、管道所传送的数据是无格式的,这要求管道的读出方与写入方必须事先约定好数据的格式,如多少字节算一个消息等。
5、管道不是普通的文件,不属于某个文件系统,其只存在于内存中。
6、管道在内存中对应一个缓冲区。不同的系统其大小不一定相同。
7、从管道读数据是一次性操作,数据一旦被读走,它就从管道中被抛弃,释放空间以便写更多的数据。
8、管道没有名字,只能在具有公共祖先的进程之间使用
1.2 无名管道的创建 -- pipe函数
#include <unistd.h>
int pipe(int pipefd[2]);
功能:
创建一个有名管道,返回两个文件描述符负责对管道进行读写操作
参数:
pipefd:int型数组的首地址,里面有两个元素
pipefd[0] 负责对管道执行读操作
pipefd[1] 负责对管道执行写操作
返回值:
成功:0
失败:‐1
案例
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char const *argv[])
{
//使用pipe创建一个无名管道
int fd_pipe[2];
if(pipe(fd_pipe) == -1)
{
perror("fail to pipe");
exit(1);
}
printf("fd_pipe[0] = %d\n", fd_pipe[0]);
printf("fd_pipe[1] = %d\n", fd_pipe[1]);
//对无名管道执行读写操作
//由于无名管道给当前用户进程两个文件描述符,所以只要操作这两个文件
//描述符就可以操作无名管道,所以通过文件IO中的read和write函数对无名管道进行操作
//通过write函数向无名管道中写入数据
//fd_pipe[1]负责执行写操作
//如果管道中有数据,再次写入的数据会放在之前数据的后面,不会把之前的数据替换
if(write(fd_pipe[1], "hello world", 11) == -1)
{
perror("fail to write");
exit(1);
}
write(fd_pipe[1], "nihao beijing", strlen("nihao beijing")+1);
//通过read函数从无名管道中读取数据
//fd_pipe[0]负责执行读操作
//读取数据时,直接从管道中读取指定个数的数据,如果管道中没有数据了,则read函数会阻塞等待
char buf[32] = "";
ssize_t bytes;
if((bytes = read(fd_pipe[0], buf, 20)) == -1)
{
perror("fail to read");
exit(1);
}
printf("buf = [%s]\n", buf);
printf("bytes = %ld\n", bytes);
bytes = read(fd_pipe[0], buf, sizeof(buf));
printf("buf = [%s]\n", buf);
printf("bytes = %ld\n", bytes);
return 0;
}
运行结果
第一次读了二十个字符,第二次读了剩下的;
1.3 无名管道实现进程间通信
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
//使用无名管道实现父子进程间的通信
//由于无名管道创建之后给当前进程两个文件描述符,所以如果是完全不相关的进程
//无法获取同一个无名管道的文件描述符,所以无名管道只能在具有亲缘关系的进程间通信
int main(int argc, char const *argv[])
{
//创建一个无名管道
int pipefd[2];
if(pipe(pipefd) == -1)
{
perror("fail to pipe");
exit(1);
}
//使用fork函数创建子进程
pid_t pid;
if((pid = fork()) < 0)
{
perror("fail to fork");
exit(1);
}
else if(pid > 0) // 父进程
{
//父进程负责给子进程发送数据
char buf[128] = {};
while(1)
{
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
if(write(pipefd[1], buf, sizeof(buf)) == -1)
{
perror("fail to write");
exit(1);
}
}
}
else //子进程
{
//子进程接收父进程的数据
char buf[128] = "";
while(1)
{
if(read(pipefd[0], buf, sizeof(buf)) == -1)
{
perror("fail to read");
exit(1);
}
printf("from parent: %s\n", buf);
}
}
return 0;
}
执行结果
注意:
利用无名管道实现进程间的通信,都是父进程创建无名管道,然后再创建子进程,子进 程继承父进程的无名管道的文件描述符,然后父子进程通过读写无名管道实现通信