1. 核心理论
有名管道又称为
FIFO文件,因此我们对有名管道的操作可以采用操作文件的方式,如使用open,write,read等。
有名管道可以用于任意进程间通信。
FIFO文件对比普通文件
1. 读取Fifo文件的进程只能以“RDONLY”方式打开。
2. 写Fifo文件的进程只能以“WRONLY”方式打开。
3. Fifo文件里面的内容被读取后,就消失了,但是普通文件的内容被读取后还存在
2.函数学习
创建有名管道
函数名:mkfifo
函数原型:int mkfifo(const char *pathname,mode_t mode);
函数功能:创建一个FIFO文件
头文件: <sys/types.h> <sys/stat.h>
返回值: 成功:0 失败:-1
参数说明: pathname:要创建的带路径的文件名 mode:文件的访问权限
删除有名管道
函数名:unlink
函数原型:int unlink(const char *pathname);
函数功能: 删除文件(包括fifo文件)
头文件: <unistd.h>
返回值:成功:0 失败:-1
参数说明:pathname:指明要删除的文件名(带路径)
3. 综合实例
任意两个进程利用有名管道通讯
/*fifo_write.c*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
void main()
{
int fd;
/*创建fifo文件*/
mkfifo("/tmp/myfifo",666);
/*打开fifo文件*/
fd = open("/tmp/myfifo",O_WRONLY);
/*写入数据到fifo文件*/
write(fd,"hello fifo",11);
close(fd);
}
/*fifo_read.c*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
void main()
{
int fd;
char c_buff[15];
fd = open("/tmp/myfifo",O_RDONLY);
read(fd,c_buff,11);
printf("read %s\n", c_buff);
close(fd);
unlink("/tmp/myfifo");
}
gcc fifo_write.c -o fifo_write
gcc fifo_read.c -o fifo_read
./fifo_write 此时写进程处于阻塞状态
./fifo_read 此时读取到数据,写进程也结束了