有名管道实现简易版聊天功能

有名管道实现简易版聊天功能_第1张图片

简单的代码,只能你写一句 我回一句 依次循环

//chat A

#include
#include
#include 
#include 
#include
#include
#include
int main() {
    //1.判断是否有有名管道
    int ret = access("fifo1", F_OK);
    if(ret == -1) {
        perror("创建对应的管道\n");
        ret = mkfifo("fifo1", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    ret = access("fifo2", F_OK);
    if(ret == -1) {
        perror("创建对应的管道\n");
        ret = mkfifo("fifo2", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    //2.以只写的方式打开fifo1
    int fdw = open("fifo1", O_WRONLY);
    if(fdw == -1){
        perror("open");
        exit(0);
    }
    printf("打开fifo1成功,等待写入...\n");

    //3.以只读的方式打开fifo2
    int fdr = open("fifo2", O_RDONLY);
    if(fdr == -1){
        perror("open");
        exit(0);
    }
    printf("打开fifo2成功,等待读取...\n");

    //4循环的写读数据
    char buf[1024] = {0};
    while (1)
    {
        memset(buf, 0, 1024);
        fgets(buf, 1024, stdin);
        //写
        ret = write(fdw, buf, sizeof(buf));
        if(ret == -1){
            perror("write");
            exit(0);
        }

        //读
        memset(buf, 0, 1024);
        ret = read(fdr, buf, 1024);
        if(ret == -1){
            perror("read");
            exit(0);
        }
        printf("buf: %s\n", buf);
    }
    close(fdr);
    close(fdw);

    return 0;
}
// chat B


#include
#include
#include 
#include 
#include
#include
#include
int main() {
    //1.判断是否有有名管道
    int ret = access("fifo1", F_OK);
    if(ret == -1) {
        perror("创建对应的管道\n");
        ret = mkfifo("fifo1", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    ret = access("fifo2", F_OK);
    if(ret == -1) {
        perror("创建对应的管道\n");
        ret = mkfifo("fifo2", 0664);
        if(ret == -1) {
            perror("mkfifo");
            exit(0);
        }
    }

    //2.以只du的方式打开fifo1
    int fdr = open("fifo1", O_RDONLY);
    if(fdr == -1){
        perror("open");
        exit(0);
    }
    printf("打开fifo1成功,等待写入...\n");

    //3.以只xie的方式打开fifo2
    int fdw = open("fifo2", O_WRONLY);
    if(fdw == -1){
        perror("open");
        exit(0);
    }
    printf("打开fifo2成功,等待写入...\n");

    //4循环的写读数据
    char buf[1024];
    while (1)
    {
        //读
        memset(buf, 0, 1024);
        ret = read(fdr, buf, 1024);
        if(ret == -1){
            perror("read");
            exit(0);
        }
        printf("buf: %s\n", buf);

        memset(buf, 0, 1024);
        fgets(buf, 1024, stdin);
        //写
        ret = write(fdw, buf, sizeof(buf));
        if(ret == -1){
            perror("write");
            exit(0);
        }
    }
    close(fdr);
    close(fdw);

    return 0;
}

你可能感兴趣的:(Linux编程入门,算法,linux,运维)