摘要: 总结了有名管道和普通文件的区别,有名管道的各种操作函数,最后给出一个读写实例加深理解。
一、有名管道
有名管道FIFO被创建之后,操作和文件类似,和有名管道一样,数据写进去读走,读走之后就没有了,不同的是以下两点:
1.读取Fifo文件的进程只能以”O_RDONLY”方式打开fifo文件。
2.写Fifo文件的进程只能以”O_WRONLY”方式打开fifo文件。
二、有名管道操作
1.创建有名管道
函数原型:int mkfifo(const char* pathname,mod_t mode)
函数功能:创建有名管道fifo文件
头文件:include <sys/types.h> include <sys/stat.h>
返回值:成功返回0,失败返回-1
函数参数:pathname:要创建的fifo的带路径的文件名
mod:创建的fifo文件的访问权限
2.删除有名管道
函数原型:int unlink(const char* pathname)
函数功能:删除有名管道文件
头文件:include <unistd.h>
返回值:成功返回0,失败返回-1
函数参数:pathname:要删除的fifo的带路径的文件名
3.打开有名管道
fd= open(“pathname”,O_RDONLY/O_WRONLY);
4.关闭有名管道
close(fd)
5.读有名管道
read(fd,buf,count)
6.写有名管道
write(fd,buf,count)
三、实例
创建一个有名管道,往里面写一些数据,然后再使用另一个进程读走,并关闭有名管道,删除管道文件。
fifo_write.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
intfd=0;
charbuf1[30]={"I write this to fifo!"};
/*创建有名管道*/
if(mkfifo("/tmp/my_fifo",0666)<0)
{
perror("creatfifo failure!");
exit(0);
}
/*打开有名管道*/
fd= open("/tmp/my_fifo",O_WRONLY);
/*向其中写数据*/
write(fd,buf1,30);
/*关闭管道*/
close(fd);
return0;
}
fifo_read.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void)
{
intfd=0;
charbuf2[30];
/*打开有名管道*/
fd= open("/tmp/my_fifo",O_RDONLY);
/*从其中读数据并显示*/
read(fd,buf2,30);
printf("Iread:%s\n",buf2);
/*关闭管道并删除该文件*/
close(fd);
unlink("/tmp/my_fifo");
return0;
}
编译完成后,先运行./fifo_write,然后写进程会阻塞,这个我还不太明白,应该是默认阻塞方式了,相信应该还有非阻塞方式,再运行读进程之后,会读出我们需要的结果,就是程序中的一句话。
这篇帖子就总结到这里吧,如有不正确的地方还请指出,大家共同进步!