命名管道(FIFO)
命名管道和基本的管道基本相同,但是也有一些显著的不同;
1)命名管道是在文件系统中,作为一个特殊的设备文件而存在的
2)不同祖先进程之间可以通过管道共享数据
3)当共享管道的进程执行完所有的I/O操作以后,命名管道将继续保存在文件系统中以便以后使用
4)管道只能由相关进程使用,他们共同的祖先进程创建了管道。但是,通过FIFO,不相关的进程也能交换数据
命名管道的创建:
#include<sys/types.h>
#include<sys/stat.h>
int mkfifo(const char *pathname,mode_t mode); filename为要创建的文件名;mode与文件的打开模式基本类似;
返回:若成功则为0,若出错则返回-1
一旦已经用mkfifo创建了一个FIFO,确实,一般的文件I/O函数(close,open,read,write,unlink等)都可用于FIFO;
//pipe_read.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#define FIFO "/tmp/myfifo"
int main(int argc,char *argv[])
{
int fd;
char buff[100];
int n_read;
if(mkfifo(FIFO,O_CREAT|O_EXCL)<0)
{
if(errno == EEXIST)
{
printf("cannot create fifo,have a fifo yet\n");
}
}
printf("preparing for reading...\n");
if((fd=open(FIFO,O_RDONLY,0766))<0)
{
printf("open fifo error!\n");
exit(1);
}
while(1)
{
memset(buff,0,sizeof(buff));
if((n_read=read(fd,buff,10))==-1)
{
if(errno == EAGAIN)
{
printf("no data yet\n");
}
}
else
{
printf("read len = %d str = %s from FIFO, len = %d\n", strlen(buff), buff, n_read);
}
sleep(1);
}
return 0;
}
//pipe_write.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#define FIFO "/tmp/myfifo"
int main(int argc,char *argv[])
{
int fd;
int n_write;
char w_buff[100];
if(argc==1)
{
printf("argc error\n");
exit(1);
}
if((fd=open(FIFO,O_WRONLY,0766))<0)
{
if(errno == ENXIO)
{
printf("open error! no reading process\n");
}
printf("open error\n");
exit(1);
}
strcpy(w_buff,argv[1]);
while(1)
{
if((n_write=write(fd,w_buff,strlen(w_buff)))==-1)
{
if(errno == EAGAIN)
{
printf("The FIFO has not been read yet\n");
}
}
else
{
printf("write str is %s to FIFO\n",w_buff);
}
sleep(1);
}
close(fd);
}