天天看點

【程序間通信】有名管道實作程序間通信詳解讀寫操作

無名管道類似于無名管道,一般都會和無名管道比較着來說

無名管道的建立

【程式間通信】有名管道實作程式間通信詳解讀寫操作

特點

  • 用于同一台PC機的兩個程序,可以是親緣程序,也可以是不相關的程序
  • 通過檔案IO操作管道
  • 不支援lseek等跳轉光标函數
  • 遵循先進先出的原則
  • 存在于檔案系統中,可以看到。檔案類型為p(管道檔案)

讀寫操作

讀操作

  • 如果之前fifo管道内沒有資料,讀程序就會一直阻塞,一直阻塞到有資料寫入或FIFO管道寫端關閉

寫操作

  • 隻要FIFO中有空間,資料就可以寫入,若空間不足,寫程序就會阻塞,直到資料全部寫入

讀端代碼

/*************************************************************************
	> File Name: fifo_one.c
	> 功能:建立一個管道,此程式用來讀出管道中的資料 
	> Mail: 
	> Created Time: Thu 15 Aug 2019 12:45:50 AM PDT
 ************************************************************************/

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

int main()
{
    int fifo=0;
    int fd=0;
    int ret=0;
    char buf[1024]={0};
//建立一個管道
   fifo= mkfifo("/home/linux/Desktop/myfifo",0666);
    if(fifo<0)
    {
        perror("mkfifo error");
        exit(-1);
    }
//以隻讀模式,打開一個管道
    fd=open("/home/linux/Desktop/myfifo",O_RDONLY);
    if(fd<0)
    {
        perror("open error");
        exit(-2);
    }
    while(1)
    {
        ret=read(fd,buf,sizeof(buf));
        if(ret<0)
        {
            perror("read error");
            exit(-3);
        }
        if(ret==0)
        {
            printf("這次什麼也沒有讀到\n");
            exit(66);
        }
        printf("這次讀到的東西是%s\n",buf);
        memset(buf,0,sizeof(buf));
    }
    close(fd);
    remove("/home/linux/Desktop/myfifo");
return 0;
}
           

寫端代碼

/*************************************************************************
	> File Name: fifo_two.c
	> Author: 
	> Mail: 
	> Created Time: Thu 15 Aug 2019 01:34:46 AM PDT
 ************************************************************************/

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

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

//以隻寫模式打開一個管道檔案
    fd=open("/home/linux/Desktop/myfifo",O_WRONLY);
    if(fd<0)
    {
        perror("open error");
        exit(-1);
    }
    while(1)
    {
        gets(buf);
        write(fd,buf,sizeof(buf));
        memset(buf,0,sizeof(buf));
    }
return 0;
}
           

運作示範

【程式間通信】有名管道實作程式間通信詳解讀寫操作

繼續閱讀