(本节笔记的实验代码可参考这里,不过,应该再可以优化一下,好像有bug)
1. 有名管道的基本概念——FIFO文件,可用open,read,write等操作方式。
2. 与普通的文件的区别:
读取FIFO文件的进程只能以“RDONLY”方式打开FIFO文;
写FIFO文件的进程只能以“WRONLY”方式打开FIFO文件;
FIFO文件里面的内容被读取后,就消失了,普通文件被读取后还存在。
3. 函数学习——有名管道
3.1 创建有名管道
函数名:
mkfifo
函数原型:(man 3 mkfifo)
int mkfifo( const char *pathname, mode_t mode);
函数功能:
创建有名管道(FIFO文件)
所属头文件:
<sys/types.h> <sys/stat.h>
返回值:
成功:返回0 失败:返回-1
参数说明:
pathname:带路径的待创建的FIFO文件
mode:FIFO文件的打开权限
3.2 删除有名管道
函数名:
unlink
函数原型:(man 2 unlink)
int unlink( const char *pathname);
函数功能:
删除有名管道(文件)
所属头文件:
<unistd.h>
返回值:
成功:返回0 失败:返回-1
参数说明:
pathname:待删除含路径的文件名
4. 综合实例——实现任意两个进程之间的通信
4.1 touch write_fifo.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char ** argv)
{
int fd;
mkfifo("/tmp/myfifo", 0666);
fd = open("/tmp/myfifo", O_WRONLY);
write(fd, "hello fifo", 11);
printf("Already write [hello fifo]\n"); /* 由于read进程未读取消息而阻塞时,该语句没被执行 */
close(fd);
return 0;
}
4.2 touch read_fifo.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char ** argv)
{
char c_buf[15];
int fd;
fd = open("/tmp/myfifo", O_RDONLY);
read(fd, "c_buf", 11);
printf("read %s \n", c_buf);
close(fd);
unlink("/tmp/myfifo");
return 0;
}