服务器 
首页 > 服务器 > 浏览文章

Linux 进程通信之FIFO的实现

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

FIFO通信(first in first out)

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

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

man 3 mkfifo

#include <sys/types.h>
#include <sys/stat.h>
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 <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

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

file_r.c 读端

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

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

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

上一篇:linux DMA接口知识点详解
下一篇:linux压缩文件命令zip的实例用法
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网