资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Linux进程通信之FIFO如何实现

这篇文章给大家分享的是有关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 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 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

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系统

Linux是一种免费使用和自由传播的类UNIX操作系统,是一个基于POSIX的多用户、多任务、支持多线程和多CPU的操作系统,使用Linux能运行主要的Unix工具软件、应用程序和网络协议。

感谢各位的阅读!关于“Linux进程通信之FIFO如何实现”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


网站标题:Linux进程通信之FIFO如何实现
网址分享:http://cdkjz.cn/article/gooccc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220