1. 程式人生 > >用命名管道實現兩個程序間通訊

用命名管道實現兩個程序間通訊

  • 首先說明一下匿名管道和命名管道之間的區別

  • 匿名管道根據其名字就可以理解到這個管道是隱藏在深海當中不可間的,使用我們程序間要是沒有點練習連這條管道都找不到。

  • 但是如果我們嗯是想在兩個不相關的檔案當中通訊的話,憑自己的理解來說我們無法找到這個管道,不相關檔案就無法通訊。

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

  • 通過命令建立命名管道的檔案

$ 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;
}

  • 分別開啟兩個中端視窗執行一下。

在這裡插入圖片描述
在這裡插入圖片描述

  • 來分別看一下寫入端程式,是否在輸入端視窗顯示出來。

在這裡插入圖片描述
在這裡插入圖片描述
具體就這樣了啊,另外需要注意一下讀端是否有資料可以讀,寫端是否資料會寫滿,是否最後快滿時候不是原子輸入了