天天看點

linux程序通信-有名管道

1.核心理論:

  • 有名管道:有名管道又稱FIFO檔案,是以我們對有名管道的操作可以采用操作檔案的方法,如使用open 、read 、write等函數。
  • fifo檔案與普通檔案的對比
FIFO檔案 普通檔案
讀取FIFO檔案的程序隻能以“RDONLY“方式打開fifo檔案 任意方式
寫FIFO 檔案的程序隻能以“WRONLY”方式打開fifo檔案 任意方式
fifo檔案讀取後就消失了管道檔案的特點 普通檔案内容被讀取後,還存在

2.函數學習

  • 建立有名管道函數

    函數原型:int mkfifo(const char *pathname , mode_t mode)

    頭檔案:sys/types.h sys/stat.h

    功能:建立一個fifo檔案

    傳回值:成功傳回0,失敗傳回 -1

    參數:pathname:要建立的檔案名(含路徑),mode:表明這個檔案的通路權限

  • 删除有名管道檔案

    函數原型:int unlink(const char *pathname ,)

    頭檔案:unistd.h

    功能:删除一個檔案名

    傳回值:成功傳回0,失敗傳回-1或者errno

    參數:pathname: 要删除的檔案名(含路徑)

3.有名管道程式設計

  • 寫程序程式
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

void main()
{
    int fd;
    char c_buf[];

    mkfifo("/home/shunzhi/apply/lesson14/test",);

    fd = open("/home/shunzhi/apply/lesson14/test",O_WRONLY);

    if(fd<)
        printf("mkfifo the file fail!\n");

    write(fd,"hello world",);
    close(fd);

    unlink("/home/shunzhi/apply/lesson14/test");
}
           
  • 讀程序程式
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

void main()
{
    int fd;
    char c_buf[];

    mkfifo("/home/shunzhi/apply/lesson14/test",);


    fd = open("/home/shunzhi/apply/lesson14/test",O_RDONLY);
    read(fd,c_buf,);
    printf("printf fifofile : %s\n",c_buf);
    close(fd);

    unlink("/home/shunzhi/apply/lesson14/test");
}
           

注意:

  • 對于程序間的有名管道通信的了解

    首先,兩個程序必須同時運作,這樣管道才被建立起來,才能通信。

    其次,通訊結束後,兩個程序才會結束,也就是管道斷開;若通訊未完成,則程序兩個程序始終處于等待狀态。

    譬如讀寫有名管道管道:先運作寫fifo檔案,然後讀取fifo檔案,讀取完成後,兩個程序同時結束;如果其中一方未完成則兩個程序始終處于等待狀态。

4.有名管道和無名管道的對比

無名管道隻能用于父程序和子程序之間的通信,有名管道可以用于任意兩個程序之間的通信。

繼續閱讀