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

进程间的通信之命名管道(FIFO)

2017-04-16 20:05 417 查看
1.命名管道:

FIFO不同于管道之处在于它提供一个路径名与之关联,以FIFO的文件形式存储于文件系统中。命名管道是一个存在与硬盘上的文件,因此,即使进程与创建FIFO的进程不存在亲缘关系,可以在任何两个进程之间通信,只要可以访问该路径,就能够通过FIFO 相互通信。值得注意的是,FIFO(first input first output)总是按照先进先出的原则工作,第一个被写入的数据将首先从管道中读出。

2.命名管道的创建与读写

(1)shell下使用命令

mknod namedpipe

(2)系统函数:在文件系统中创建一个文件

int mknod(const char *path,mode_t mod,dev_t dev);

int mkfifo(const char*path,mode_t mod)

//path是创建命名管道的全局路径,各进程都可以访问;

mod为创建的模式(读写权限)。

(3)操作:

因为命名管道是一个存在与内存的特殊文件,所有首先要open();

打开的方式有读写(O_RDWR),只读(O_RDONLY),只写(O_WRONLY)

注意:只读,调用open的函数的进程将会被阻塞直到有写方打开管道

同样,只写,调用open的函数的进程将会被阻塞直到有读方打开管道;

(4)具体代码:

write端的代码

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
int main()
{
int fd=open("./fifo",O_WRONLY) ;
if(fd<0)
return 2;
else
{

char buff[128];
while(1)
{
printf("please Enter:");
fflush(stdout);
ssize_t  s=read(0,buff,sizeof(buff));
if(s>0)
buff[s]='\0';
write(fd,buff,strlen(buff));  }
close(fd);
}
return 0;
}


read端的代码

#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
umask(0);
if(mkfifo("./fifo",0666|S_IFIFO)<0)//创建pipe
{
printf("mkfifo erro\n");
return 1;
}
else{
int fd=open("./fifo",O_RDONLY); //open pipe
sleep(10);
if(fd<0)
return 2;
else
{
char buff[128];
while(1)
{
ssize_t  s=read(fd,buff,sizeof(buff)-1);
if(s==0)
{
close(fd);
exit(0);
}
if(s>0)
{
buff[s]='\0';
printf("%s",buff);
}
}
close(fd);

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