简介
- 匿名管道,由于没有名字 ,只能进行情缘关系的进程间通信,如父子进程。
- 有名管道(FIFO),命名管道或FIFO文件。关键点:提供了一个路径名与之关联,以FIFO的文件形式存在于文件系统之中·,打开方式与普通文件的打开方式是一样的,所以即使不存在亲缘关系,只要可以访问路径,就可以通过FIFO通信、
数据结构:环形队列,first in first out先入先出 queue
与匿名管道的不同点:
使用:
/*
创建FIFO文件
1.通过命令 : mkfifo + 名字
2.通过函数 :int mkfifo(const char *pathname,mode_t mode);
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
参数:pathname:管道名称路径
mode_t:文件的权限,是一个8进制的数
返回值:成功返回0,失败返回-1,并设置错误号
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
int main(){
int ret = mkfifo("fifo1",0664);
if(ret == -1){
perror("mkfifo");
exit(0);
}
}
实现两个进程之间通信:
write
//从管道中读取数据
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main(){
//1.打开管道文件
int fd = open("test",O_RDONLY);
if (fd == -1)
{
perror("open");
exit(0);
/* code */
}
//读数据
while(1){
char buf[1024] = {0};
int len = read(fd,buf,sizeof(buf));
if(len == 0 )
{
printf("写端断开连接..\n");
break;
}
printf("recv buf : %s\n",buf);
}
return 0;
}
read
// 向管道写入数据
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main(){
//1.判断文件是否存在
int ret = access("test",F_OK);
if(ret == -1)
{
printf("管道不存在,创建管道\n");
//2.创建管道文件
int ret = mkfifo("test",0664);
if(ret == -1)
{
perror("mkfifo");
exit(0);
}
}
//3.打开管道,以只写的方式
int fd = open("test",O_WRONLY);
if (fd == -1)
{
perror("open");
exit(0);
/* code */
}
//数据
for (int i = 0; i < 100; i++)
{
char buf[1024];
sprintf(buf,"Hello,%d\n",i);
printf("write data : %s\n",buf);
write(fd,buf,strlen(buf));
sleep(1);
/* code */
}
close(fd);
return 0;
}