您的位置:首页 > 运维架构 > Linux

Linux系统编程:fifo有名管道的使用

2018-03-20 22:21 337 查看

fifo介绍

我们可以利用管道进行进程间通信,已经有匿名管道 为啥还要fifo 有名管道呢?有名管道是对匿名管道的一个补充,匿名管道是用在有血缘关系的进程间通信。fifo有名管道呢,可以用在任何进程间通信
函数原型 int mkfifo(const char *pathname, mode_t mode);第一个参数是匿名管道的路径,第二个参数创建有名管道的权限。当然man 手册是最好的文档,一定要自己试着去看man 手册。

fifo的使用

我们利用2个不相干的进行 通过fifo 有名管道进行通信。下面用fifo_read进程读数据,fifo_write进程写数据。

fifo_read.c

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("./fifo_read fifoName");
exit(1);
}
int res = access(argv[1],F_OK);
if(res==-1)//不可访问 或者 文件不存在
{
int re = mkfifo(argv[1],0664);
if(re==0)
{
printf("创建fifo文件成功,文件名:%s\n",argv[1]);
}else
{
perror("mkfifo error");
exit(1);
}
}
int fd = open(argv[1],O_RDONLY);
//从fifo中读数据
char temp[1024]={0};
while(1)
{
read(fd,temp,sizeof(temp));
printf("从fifo中读取数据:%s\n",temp);
}
close(fd);
return 0;
}


fifo_write.c

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("./fifo_write fifoName");
exit(1);
}
int res = access(argv[1],F_OK);
if(res==-1)//不可访问 或者 文件不存在
{
int re = mkfifo(argv[1],0664);
if(re==0)
{
printf("创建fifo文件成功,文件名:%s\n",argv[1]);
}else
{
perror("mkfifo error");
exit(1);
}
}
int fd = open(argv[1],O_WRONLY);
//往fifo中写数据
char str[100] = "hello laymond";
while(1)
{
sleep(1);
write(fd,str,sizeof(str));
printf("写入一条数据:%s\n",str);
}
close(fd);
return 0;
}

代码运行检测



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: