命名管道FIFO


  • FIFO IPC机制是利用文件管理系统中的特殊文件来标识的,可以用mkfifo命令创建一个FIFO文件

    • mkfifo tube
      ls -l tube
      
FIFO文件在磁盘上没有数据块,仅用来标识内核中的一条通道,各进程可以打开这个文件进行read/write,实际上是在读写内核通道(根本原因在于这个file结构体所指向的read、write函数和常规文件不一样),这样就实现了进程间通信。

作用

  • 实时交互

两个程序聊天

从屏幕往管道写数据

/*************************************************************************
        > File Name: readFifo.c
        > Author:
        > Mail:
        > Created Time: Sat 29 Jan 2022 01:57:30 PM CST
 ************************************************************************/

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

int main() {

    int fd = open("./tube", O_WRONLY); //只写
    if (fd == -1) {
        perror("open");
        exit(1);
    }

    char buf[1024];
    int n = read(0, buf, 1024);//从屏幕读取
    if (n < 0) {
        perror("read");
        exit(1);
    }

    write(fd, buf, n); //写到管道
    return 0;
}

从管道读数据往屏幕输出数据

/*************************************************************************
        > File Name: readFifo.c
        > Author:
        > Mail:
        > Created Time: Sat 29 Jan 2022 01:57:30 PM CST
 ************************************************************************/

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

int main() {
    char buf[1024];
    int fd = open("./tube", O_RDONLY); //只读
    if (fd == -1) {
        perror("open");
        exit(1);
    }

    ssize_t n = read(fd, buf, 20); //从管道读取数据

    if (n < 0) {
        perror("read");
        exit(1);

    }

    write(1, buf, n); //把数据写到屏幕上
    return 0;
}

文章作者: Axieyun
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Axieyun !
评论
评论
  目录