定义
fifo也被称为命名管道。未命名的管道只能在两个相关的进程之间使用,而且这两个进程还有一个共同的创建了他们的祖先进程,但是fifo,不相关的进程也能交换数据。
fifo的创建
fifo是一种文件类型,fifo的创建有两种方式。
1.直接用命令创建 mkfifo
2.利用函数创建
int mkfifo(const char *pathname,mode_t,mode)
下面用一个案例演示从一个进程发送数据到另外一个不相干的进程。
发送端:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main()
{
int fd,len,i;
char buf[4096];
fd=open("./10_myfifo",O_WRONLY);
if(fd<0)
{
sys_err("open error");
exit(1);
}
i=0;
while(1)
{
sprintf(buf,"hello fifo%d\n",i++);
write(fd,buf,strlen(buf));
sleep(1);
}
close(fd);
return 0;
}
接收端:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
int main()
{
int len;
char buf[4096];
int fd=open("./10_myfifo",O_RDONLY);
if(fd==-1)
{
sys_err("open error");
}
while(1) //循环将读取的数据写到平面镜上去
{
len=read(fd,buf,sizeof(buf));
if(len<0)
{
sys_err("read error");
exit(1);
}
write(STDOUT_FILENO,buf,len);
}
return 0;
}
打开两个终端一个运行写端,另一个运行读端,在读端会将接收到的数据输出到屏幕上,如下所示