Linux学习之系统编程篇:fifo

一、fifo 的基本概念和创建

1、特点:

(1)有名管道;
(2)伪文件:在磁盘上是一个管道文件,但对其读写操作,该文件大小都为 0。
注意:pipe 文件在磁盘上,ls -l 能查看到,但文件内数据不在磁盘上,是在内存上
(3)数据通过伪文件存放在内核区,本质仍然是内核中的缓冲区。
(4) 半双工的通信方式。

2、使用场景

没有血缘关系的进程间通信

3、创建方式

(1)命令:mkfifo 管道名
(2)函数:

int mkfifo(const char *pathname, mode_t mode); // 使用 跟 mkdir 差不多

二、fifo 实现进程间通信

1、fifo_r.c 读进程

#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc,char *argv[])
{if(argc != 2){printf("./a.out fifoname\n");return -1;}//1. 打开文件int fd = open(argv[1], O_RDONLY);if(fd < 0){perror("open err");return -1;}//2. 循环读取数据 -- 显示到屏幕char buf[256] = {0};while(1){int ret = read(fd, buf, sizeof(buf));if(ret > 0){// 读到数据printf("%s\n", buf);}else if(ret == 0){// 读到末尾 -- 写端全部关闭printf("write closed\n");break;}else {perror("read err");break;}}//3. 关闭close(fd);return 0;
}

2、fifo_w.c 写进程

#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(int argc,char *argv[])
{if(argc != 2){printf("./a.out fifoname\n");return -1;}//1. 打开fifo文件printf("begin open....\n");int fd = open(argv[1], O_WRONLY); // open 函数会等待另外一段的读打开,否则阻塞if(fd < 0){perror("open err");exit(1);}printf("end open....\n");//2. 循环写入数据char buf[256] = {0};int i = 0;while(1){memset(buf, 0x00, sizeof(buf));sprintf(buf, "xiaoming-%04d", i++);write(fd, buf, strlen(buf));sleep(1); //防止写的太快了}//3. 关闭close(fd);return 0;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部