栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > 服务器

Linux 进程通信之FIFO的实现

服务器 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux 进程通信之FIFO的实现

FIFO通信(first in first out)

FIFO 有名管道,实现无血缘关系进程通信。

  • 创建一个管道的伪文件
    • a.mkfifo testfifo 命令创建
    • b.也可以使用函数int mkfifo(const char *pathname, mode_t mode);
  • 内核会针对fifo文件开辟一个缓冲区,操作fifo文件,可以操作缓冲区,实现进程间通信–实际上就是文件读写

man 3 mkfifo

#include 
#include 
int mkfifo(const char *pathname, mode_t mode);

注意事项:

FIFOs
Opening the read or write end of a FIFO blocks until the other end is also opened (by another process or thread). See
fifo(7) for further details.

打开fifo文件时候,read端会阻塞等待write端open,write端同理,也会阻塞等待另外一段打开。

代码示例:
file_w.c 写端

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char *argv[]) {
  if(argc != 2) {
    printf("./a.out filename1n");
    return -1;
  }
  printf("begin open wn");
  int o_ret = open(argv[1], O_WRONLY);
  printf("end open wn");
  char buf[256];
  int num = 0;
  while (1) {
    memset(buf, '', sizeof(buf));
    sprintf(buf, "xiaoming--%d", num++);
    printf("strlen(buf) = %dn", strlen(buf));
    write(o_ret, buf, strlen(buf));
    sleep(1);
  }
  close(o_ret);
  return 0;
}
 

file_r.c 读端

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(int argc, char *argv[]) {
  if(argc != 2) {
    printf("./a.out filename1n");
    return -1;
  }
  printf("begin open rn");
  int o_ret = open(argv[1], O_RDONLY);
  printf("end open rn");
  char buf[256];
  int num = 0;
  while (1) {
    memset(buf, '', sizeof(buf));
    read(o_ret, buf, sizeof(buf));
    printf("strlen(buf) = %dn", strlen(buf));
    printf("read is%sn", buf);
  }
  close(o_ret);
  return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/177592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号