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 <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
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 <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
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;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值