用命名管道实现两个进程间通信

  • 首先说明一下匿名管道和命名管道之间的区别

  • 匿名管道根据其名字就可以理解到这个管道是隐藏在深海当中不可间的,使用我们进程间要是没有点练习连这条管道都找不到。

  • 但是如果我们嗯是想在两个不相关的文件当中通信的话,凭自己的理解来说我们无法找到这个管道,不相关文件就无法通信。

  • 所以我们需要使用一种特殊的管道,他的名字就是命名管道。
    创建命名管道的方法

  • 通过命令创建命名管道的文件

$ mkfifo filename
  • 通过程序中创建
int mkfifo (const char *filename,mode_t mode);

来一段单进程的简单看一下吧,fork进程下创建道理也相同,因为今天实在有事情,实现两个进程之间互斥的读写,大家照猫花老虎一下吧。

==写入目标文件==
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>

int main()
{
    char *file = "./test.fifo";
    umask(0);
    if (mkfifo(file, 0664) < 0) {
        if (errno == EEXIST) {
            printf("fifo exist!!\n");
        }else {
            perror("mkfifo");
            return -1;
        }
    }
    int fd = open(file, O_WRONLY);
    if (fd < 0) {
        perror("open error");
        return -1;
    }
    printf("open fifo success!!\n");
    while(1) {
        printf("input: ");
        fflush(stdout);
        char buff[1024] = {0};
        scanf("%s", buff);
        write(fd, buff, strlen(buff));
    }
    close(fd);
    return 0;
}

==读入文间==
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>

int main()
{
    char *file = "./test.fifo";
    umask(0);
    if (mkfifo(file, 0664) < 0) {
        if (errno == EEXIST) {
            printf("fifo exist!!\n");
        }else {
            perror("mkfifo");
            return -1;
        }
    }
    int fd = open(file, O_RDONLY);
    if (fd < 0) {
        perror("open error");
        return -1;
    }
    printf("open fifo success!!\n");
    while(1) {
        char buff[1024];
        memset(buff, 0x00, 1024);
        int ret = read(fd, buff, 1024);
        if (ret > 0) {
            printf("peer say:%s\n", buff);
        }
    }
    close(fd);
    return 0;
}

  • 分别打开两个中端窗口运行一下。

在这里插入图片描述
在这里插入图片描述

  • 来分别看一下写入端程序,是否在输入端窗口显示出来。

在这里插入图片描述
在这里插入图片描述
具体就这样了啊,另外需要注意一下读端是否有数据可以读,写端是否数据会写满,是否最后快满时候不是原子输入了

猜你喜欢

转载自blog.csdn.net/sing_Hwang/article/details/85175913
今日推荐