Linux 有名管道模拟聊天功能

1. 思路


 2. 代码实现

talkA.c

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

#define SIZE 128

/*talkA进程*/
int main(int argc, const char* argv[]) {

    int fdr = -1;
    int fdw = -1;
    int ret = -1;
    char buf[SIZE];

    // 1. 只读方式打开管道fifo_1,只写方式打开管道fifo_2
    fdr = open("fifo_1", O_RDONLY);
    if (-1 == fdr) {
        perror("open");
        return 1;
    }

    fdw = open("fifo_2", O_WRONLY);
    if (-1 == fdw) {
        perror("open");
        return 1;
    }

    // 2. 循环读写
    while (1) {
        memset(buf, 0, SIZE);
        ret = read(fdr, buf, SIZE); // 读管道
        if (ret <= 0) {
            perror("read");
            break;
        }
        printf("talkB: %s\n", buf);

        memset(buf, 0, SIZE);
        printf("我: ");
        fgets(buf, SIZE, stdin);
        if ('\n' == buf[strlen(buf) - 1]) {  // 将末尾换行符去掉
            buf[strlen(buf) - 1] = '\0';
        }

        ret = write(fdw, buf, strlen(buf)); // 写管道
        if (ret <= 0) {
            perror("write");
            break;
        }
    }

    // 3. 关闭文件描述符
    close(fdr);
    close(fdw);
    return 0;
}

talkB.c

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

#define SIZE 128

/*talkA进程*/
int main(int argc, const char* argv[]) {

    int fdr = -1;
    int fdw = -1;
    int ret = -1;
    char buf[SIZE];

    // 1. 只写方式打开管道fifo_1,只读方式打开管道fifo_2
    fdw = open("fifo_1", O_WRONLY);
    if (-1 == fdw) {
        perror("open");
        return 1;
    }

    fdr = open("fifo_2", O_RDONLY);
    if (-1 == fdr) {
        perror("open");
        return 1;
    }

    // 2. 循环写读
    while (1) {
        printf("我: ");
        memset(buf, 0, SIZE);
        fgets(buf, SIZE, stdin);
        if ('\n' == buf[strlen(buf) - 1]) {  // 将末尾换行符去掉
            buf[strlen(buf) - 1] = '\0';
        }

        ret = write(fdw, buf, strlen(buf)); // 写管道
        if (ret <= 0) {
            perror("write");
            break;
        }

        memset(buf, 0, SIZE);
        ret = read(fdr, buf, SIZE); // 读管道
        if (ret <= 0) {
            perror("read");
            break;
        }
        printf("talkA: %s\n", buf);
    }

    // 3. 关闭文件描述符
    close(fdr);
    close(fdw);
    return 0;
}

测试结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

伟大的马师兄

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

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

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

打赏作者

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

抵扣说明:

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

余额充值