天天看點

2-14 有名管道通信

(本節筆記的實驗代碼可參考這裡,不過,應該再可以優化一下,好像有bug)

1.  有名管道的基本概念——FIFO檔案,可用open,read,write等操作方式。

2.  與普通的檔案的差別:

        讀取FIFO檔案的程序隻能以“RDONLY”方式打開FIFO文;

        寫FIFO檔案的程序隻能以“WRONLY”方式打開FIFO檔案;

        FIFO檔案裡面的内容被讀取後,就消失了,普通檔案被讀取後還存在。

3.  函數學習——有名管道

    3.1  建立有名管道

        函數名:

                mkfifo

        函數原型:(man 3 mkfifo)

                int mkfifo( const char *pathname, mode_t mode);

        函數功能:

                建立有名管道(FIFO檔案)

        所屬頭檔案:

                <sys/types.h>    <sys/stat.h>

        傳回值:

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

        參數說明:

                pathname:帶路徑的待建立的FIFO檔案

                mode:FIFO檔案的打開權限

    3.2  删除有名管道

        函數名:

                unlink

        函數原型:(man 2 unlink)

                int unlink( const char *pathname);

        函數功能:

                删除有名管道(檔案)

        所屬頭檔案:

                <unistd.h>

        傳回值:

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

        參數說明:

                pathname:待删除含路徑的檔案名

4.  綜合執行個體——實作任意兩個程序之間的通信

    4.1  touch write_fifo.c

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int main(int argc, char ** argv)

{

    int fd;

    mkfifo("/tmp/myfifo", 0666);

    fd = open("/tmp/myfifo", O_WRONLY);

    write(fd, "hello fifo", 11);

    printf("Already write [hello fifo]\n");    

    close(fd);

    return 0;

}

    4.2  touch read_fifo.c

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int main(int argc, char ** argv)

{

    char c_buf[15];

    int fd;

    fd = open("/tmp/myfifo", O_RDONLY);

    read(fd, "c_buf", 11);

    printf("read %s \n", c_buf); 

    close(fd);

    unlink("/tmp/myfifo");

    return 0;

}