极简聊天——有名管道实现进程间通信

为什么说极简呢,因为下面这个程序只能从一端写另一端读。(单工通信)
注意:有名管道用于系统中任意两个进程间通信(不需要有亲缘关系)

fifo_read.c

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

int main()
{
    int ret, fd;
    char buf[100] = {0};

    ret = mkfifo("fifo.tmp", O_CREAT | O_EXCL);     //创建有名管道
    if (-1 == ret)      //创建失败
    {
        perror("fifo");
        exit(1);
    }

    fd = open("fifo.tmp", O_RDONLY);        //以只读方式打开
    if(-1 == fd)        //打开失败
    {
        perror("read");
        exit(1);
    }

    while(1)
    {
        ret = read(fd, buf, sizeof(buf));       //读出缓冲区中的内容
        if(ret == -1)
        {
            perror("read");
            exit(1);
        }
        if(!strncmp(buf, "bye", 3))     //以bye结束
        {
            break;      //跳出循环
        }

        printf("read from fifo.tmp: %s\n",buf);
        memset(buf, 0, sizeof(buf));    //清空缓冲区
        unlink("fifo.tmp"); //关掉管道文件,方便程序下次运行
    }
    return 0;
}

fifo_write.c

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

int main()
{
    char buf[100] = {0};
    int fd, ret;

    fd = open("fifo.tmp", O_WRONLY);        //以只写方式打开
    if(-1 == fd)
    {
        perror("open");
        exit(1);
    }

    while(1)
    {
        scanf("%s",buf);
        ret = write(fd, buf, strlen(buf));      //往缓冲区里面写
        if(-1 == ret)
        {
            perror("write");
            exit(1);
        }

        if(!strncmp(buf, "bye", 3))     //以bye结束
        {
            break;
        }
    memset(buf, 0, sizeof(buf));        //清空缓冲区
    }
    return 0;
}

上面两个程序(进程)前者为读,后者为写,注意第一个程序里面首先要创建一个有名管道,所以两个程序运行的先后顺序是前者先运行(此时,一直读到空)。运行结果如下:

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值