管道 mkfifio函数的使用

在这里插入图片描述
mkfifo命令生成管道文件
mkfifo函数 第一参数路径, 第二是权限

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

写入数据

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

int main(int argc, char *argv[])
{
    // 文件描述符
    int fd;
    int ret;
    //判断是否创建管道文件
    if ((ret = access("./myfifo", F_OK)) == -1)
    {
        //创建管道
        ret =  mkfifo("./myfifo", 0777);
        if (ret < 0)
        {
            perror("mkfifo error");
            return -1;
        }
    }

    //打开文件
    fd = open("./myfifo", O_RDWR);
    if (fd < 0)
    {
        perror("open error");
        return -1;
    }
    //=====================写数据到管道中============================
    while (1)
    {
        sleep(1);
        write(fd, "alpha, spider", strlen("alpha, spider"));
    }
    close(fd);
	return 0;
}

读取数据

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

int main(int argc, char *argv[])
{
    //文件描述符
    int fd;
    int ret;
    char buf[1024];
    //检测是否有管道文件
    if ((ret = access("./myfifo", F_OK)) == -1)
    {
        ret = mkfifo("./myfifo", 0777);
        if (ret < 0)
        {
            perror("mkfifo error");
            return -1;
        }
    }

    //打开管道文件
    fd = open("./myfifo", O_RDWR);
    if (fd < 0)
    {
        perror("open error");
        return -1;
    }
    //==============读取管道中数据=========================
    while (1)
    {
        //=================   设置read函数非阻塞  ==================
/*      int flags = fcntl(fd, F_GETFL);
        flags |= O_NONBLOCK;
        fcntl(fd, F_SETFL, flags);*/
        sleep(1);
        memset(buf, 0x00, sizeof(buf));
        ret = read(fd, buf, sizeof(buf));
        printf("读取数据:%d, buf = %s\n", ret, buf);
    }
    //关闭文件
    close(fd);

    return 0;
}

运行效果:
在这里插入图片描述

在这里插入图片描述
参考资料:

  1. https://blog.csdn.net/Poisx/article/details/78300726
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值