• 企业400电话
  • 微网小程序
  • AI电话机器人
  • 电商代运营
  • 全 部 栏 目

    企业400电话 网络优化推广 AI电话机器人 呼叫中心 网站建设 商标✡知产 微网小程序 电商运营 彩铃•短信 增值拓展业务
    Linux 进程通信之FIFO的实现

    FIFO通信(first in first out)

    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;
    }
    
    

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

    上一篇:Docker创建容器时目录权限踩坑
    下一篇:Linux /etc/network/interfaces配置接口方法
  • 相关文章
  • 

    © 2016-2020 巨人网络通讯

    时间:9:00-21:00 (节假日不休)

    地址:江苏信息产业基地11号楼四层

    《增值电信业务经营许可证》 苏B2-20120278

    Linux 进程通信之FIFO的实现 Linux,进程,通信,之,FIFO,的,