Linux学习笔记-命名管道(FIFO)

140 篇文章 11 订阅

目录

 

理论

例子


理论

在int mkfifo(const char *pathname, mode_t mode)

成功返回o,出错返回-1

他包含在头文件:

#include <sys/types.h>

#include <sys/stat.h>

 

 

这里要注意:

1.只要对FIFO有适当的访问权限,FIFO可用在任何两个没有任何关系的进程之间通信;

2.本质是内核中的一块缓存,另在文件系统中以一个特殊的设备文件(管道文件)存在;

3.在文件系统中只有一个索引块存放文件的路径,没有数据块,所有数据存放在内核中;

4.命名管道必须在读和写中同时打开,否则单独读或者单独写会发生阻塞;

5.命令mkfifo创建命名管道(命令内部调用mkfifo函数)

6.对FIFO的操作与操作普通文件一样;

 

例子

程序运行截图如下:

 

 

fifo_read.c


#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <memory.h>

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

        if(argc < 2){

                printf("usage:%s fifo\n", argv[0]);
                exit(1);
        }

        printf("open fifo read... \n");

        int fd = open(argv[1], O_RDONLY);
        if(fd < 0){

                perror("open error");
                exit(1);
        }
        else{

                printf("open file success:%d\n", fd);
        }

        //从命名管道中读取数据
        char buf[512];
        memset(buf, 0, sizeof(buf));
        while(read(fd, buf, sizeof(buf)) < 0){

                perror("read error");
        }
        printf("%s\n", buf);

        close(fd);
        exit(0);
}


fifo_write.c源码如下:

#include <unistd.h>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

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

        if(argc < 2){

                printf("usage:%s fifo\n", argv[0]);
                exit(1);
        }

        printf("open fifo write ... \n");

        //打开命名管道
        int fd = open(argv[1], O_WRONLY);
        if(fd < 0){

                perror("open error");
                exit(1);
        }
        else{

                printf("open fifo success:%d\n", fd);
        }
        char *s = "12345678901234";
        size_t size = strlen(s);
        if(write(fd, s, size) != size){

                perror("write error");
        }
        close(fd);

        exit(0);
}

这里要创建一个pip,命令如下:mkfifo s.pipo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值