FIFO 使用介绍


一、FIFO 简介

无名管道由于没有名字,因此只能用于亲缘关系的进程间通信
命名管道提供了一个路径名与之关联,以 FIFO 的文件形式存在于文件系统中,这样即使进程不存在亲缘关系,只要可以访问该路径就能够彼此通信
FIFO 在文件系统中作为一个特殊的文件而存在,文件内容存放在内存中,当使用 FIFO 的进程退出后,FIFO 文件将继续保存在文件系统中以便以后使用

二、FIFO 示例代码

1. int mkfifo( const char *pathname, mode_t mode);

创建命名管道,后期操作把这个命名管道当做普通文件一样进行操作:open()、write()、read()、close()
通信过程中若写进程先退出了,就算命名管道里没有数据,调用 read() 函数读数据时不阻塞;若写进程又重新运行,则调用 read() 函数读数据时又恢复阻塞
mode: 文件的权限,与打开普通文件的 open() 函数中的 mode 参数相同

// 写进程
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    int fd;

    mkfifo("my_fifo", 0666);
    fd = open("my_fifo", O_WRONLY);
    char send[128] = "Hello world";
    write(fd, send, strlen(send));
    printf("write to my_fifo buf=%s\n", send);
    while(1);
    return 0;
}


// 读进程
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    int fd;

    mkfifo("my_fifo", 0666);
    fd = open("my_fifo", O_RDONLY);
    while (1)
    {
        char recv[128] = {0};
        read(fd, recv, sizeof(recv));
        printf("read from my_fifo buf=[%s]\n", recv);
        sleep(1);
    }
    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值