有名管道的概念及创建及使用
1概念:它是一种文件类型,在文件系统中可以看到。程序中可以查看文件stat结构中st_mode成员的值来判断文件是否是FIFO文件。创建一个FIFO文件类似于创建文件,FIFO文件就像普通文件一样。FIFO中可以很好地解决在无关进程间数据交换的要求,并且由于它们是存在于文件系统中的,这也提供了一种比匿名管道更持久稳定的通信办法。
FIFO的通信方式类似于在进程中使用文件来传输数据,只不过FIFO类型文件同时具有管道的特性。在数据读出时,FIFO管道中同时清除数据。在shell中mkfifo命令可以建立有名管道,下面通过一个实例来帮助读者理解FIFO。
2有名管道编程实战:
有名管道一般用的多的是令其堵塞,因而在创建管道后开始读取时,需要另一进程进行写,才能正确读取到。
创建有名管道编程及写入数据:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
int n_write;
int cnt;
cnt=0;
char *str="wencai love pingping";//要发送的数据,可自己决定
fd=open("./file1",O_WRONLY);
printf("open sucesess\n");
while(1){
n_write=write(fd,str,strlen(str));
sleep(1);
cnt++;
if(cnt==4){
break;
}
}
close(fd);
return 0;
}
读取管道中的数据:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
int n_read;
int cnt=0;
char buf[30]={0};
if((mkfifo("./file1",0600)==-1)&&errno!=EEXIST){ //查看是否有创建成功的管道
printf("creat failuer\n");
perror("why");
}
fd=open("./file1",O_RDONLY);
printf("open sucesess\n");
while(1){
memset(buf,'\0',sizeof(buf));//清空收到的消息
n_read=read(fd,buf,30);//读取管道中的数据
printf("read %d byte from,context:%s\n",n_read,buf);
if(cnt++==4){
break;
}
}
close(fd);
return 0;
}
然后我们来看看运行后的效果
运行程序后,可以看到字符串被传递了过去,从而通过有名管道实现了进程间的通信。