linux程式設計之pipe()函式

2puT發表於2016-07-14


管道是一種把兩個程式之間的標準輸入和標準輸出連線起來的機制,從而提供一種讓多個程式間通訊的方法,當程式建立管道時,每次

都需要提供兩個檔案描述符來操作管道。其中一個對管道進行寫操作,另一個對管道進行讀操作。對管道的讀寫與一般的IO系統函式一

致,使用write()函式寫入資料,使用read()讀出資料。

#include<unistd.h>

int pipe(int filedes[2]);

返回值:成功,返回0,否則返回-1。引數陣列包含pipe使用的兩個檔案的描述符。fd[0]:讀管道,fd[1]:寫管道。

必須在fork()中呼叫pipe(),否則子程式不會繼承檔案描述符。兩個程式不共享祖先程式,就不能使用pipe。但是可以使用命名管道。

 

當管道進行寫入操作的時候,如果寫入的資料小於128K則是非原子的,如果大於128K位元組,緩衝區的資料將被連續地寫入

管道,直到全部資料寫完為止,如果沒有程式讀取資料,則將一直阻塞,如下:

在上例程式中,子程式一次性寫入128K資料,當父程式將全部資料讀取完畢的時候,子程式的write()函式才結束阻塞並且

返回寫入資訊。

命名管道FIFO

管道最大的劣勢就是沒有名字,只能用於有一個共同祖先程式的各個程式之間。FIFO代表先進先出,單它是一個單向資料流,也就是半雙工,和

管道不同的是:每個FIFO都有一個路徑與之關聯,從而允許無親緣關係的程式訪問。  

        #include <sys/types.h>

        #include <sys/stat.h>

      int mkfifo(const char *pathname, mode_t mode);
     這裡pathname是路徑名,mode是sys/stat.h裡面定義的建立檔案的許可權.

以下示例程式來自:http://blog.chinaunix.net/uid-20498361-id-1940238.html

  有親緣關係程式間的fifo的例子

/*
 * 有親緣關係的程式間的fifo的使用
 * fifo 使用的簡單例子
 */

#include "../all.h"

#define FIFO_PATH "/tmp/hover_fifo"


void 
do_sig(int signo)
{
    if (signo == SIGCHLD)
        while (waitpid(-1, NULL, WNOHANG) > 0)
            ;
}


int
main(void)
{
    int ret;
    int fdr, fdw;
    pid_t pid;

    char words[10] = "123456789";
    char buf[10] = {'\0'};    
    
    // 建立它,若存在則不算是錯誤,
    // 若想修改其屬性需要先開啟得到fd,然後用fcntl來獲取屬性,然後設定屬性.

    if (((ret = mkfifo(FIFO_PATH, FILE_MODE)) == -1) 

                     && (errno != EEXIST))
        perr_exit("mkfifo()");
    fprintf(stderr, "fifo : %s created successfully!\n", FIFO_PATH);

    signal(SIGCHLD, do_sig);

    pid = fork();
    if (pid == 0) { // child

        if ((fdr = open(FIFO_PATH, O_WRONLY)) < 0) // 開啟fifo用來寫
            perr_exit("open()");
        sleep(2);

        // 寫入資料
        if (write(fdr, words, sizeof(words)) != sizeof(words)) 
            perr_exit("write");
        fprintf(stderr, "child write : %s\n", words);
        close(fdw);
    } else if (pid > 0) { // parent

        if ((fdr = open(FIFO_PATH, O_RDONLY)) < 0) // 開啟fifo用來讀

            perr_exit("open()");

        fprintf(stderr, "I father read, waiting for child ...\n");
        if (read(fdr, buf, 9) != 9) //讀資料
            perr_exit("read");

        fprintf(stderr, "father get buf : %s\n", buf);
        close(fdr);
    }
    // 到這裡fifo管道並沒有被刪除,必須手動呼叫函式unlink或remove刪除.

    return 0;    
}


從例子上可以看出使用fifo時需要注意:
*fifo管道是先呼叫mkfifo建立,然後再用open開啟得到fd來使用.
*在開啟fifo時要注意,它是半雙工的的,一般不能使用O_RDWR開啟,而只能用只讀或只寫開啟.

   fifo可以用在非親緣關係的程式間,而它的真正用途是在伺服器和客戶端之間. 由於它是半雙工的所以,如果要進行客戶端和伺服器雙方的通訊的話,

每個方向都必須建立兩個管道,一個用於讀,一個用於寫.

下面是一個伺服器,對多個客戶端的fifo的例子:

server 端的例子:



/*
 * FIFO server
 */

#include "all.h"

int
main(void)
{
    int fdw, fdw2;
    int fdr;
    char clt_path[PATH_LEN] = {'\0'};
    char buf[MAX_LINE] = {'\0'};
    char *p;
    int n;
    
    if (mkfifo(FIFO_SVR, FILE_MODE) == -1 && errno != EEXIST)    
        perr_exit("mkfifo()");    
    if ((fdr = open(FIFO_SVR, O_RDONLY)) < 0)    
        perr_exit("open()");
    /* 
     * 根據fifo的建立規則, 若從一個空管道或fifo讀, 

     * 而在讀之前管道或fifo有開啟來寫的操作, 那麼讀操作將會阻塞 
     * 直到管道或fifo不開啟來讀, 或管道或fifo中有資料為止. 

     *

     * 這裡,我們的fifo本來是開啟用來讀的,但是為了,read不返回0,

     * 讓每次client端讀完都阻塞在fifo上,我們又開啟一次來讀.
     * 見unpv2 charper 4.7
     */
    if ((fdw2 = open(FIFO_SVR, O_WRONLY)) < 0)    
        fprintf(stderr, "open()");
    
    while (1) {
        /* read client fifo path from FIFO_SVR */

     /* 這裡由於FIFO_SVR有開啟來寫的操作,所以當管道沒有資料時, 

      * read會阻塞,而不是返回0. 

      */
        if (read(fdr, clt_path, PATH_LEN) < 0) {
            fprintf(stderr, "read fifo client path error : %s\n", strerror(errno));    
            break;
        }
        if ((p = strstr(clt_path, "\r\n")) == NULL) {
            fprintf(stderr, "clt_path error: %s\n", clt_path);
            break;
        }
        *p = '\0';
        DBG("clt_path", clt_path);
        if (access(clt_path, W_OK) == -1) { // client fifo ok, but no permission

            perror("access()");    
            continue;
        }
        /* open client fifo for write */
        if ((fdw = open(clt_path, O_WRONLY)) < 0) {
            perror("open()");    
            continue;
        }
        if ((n = read(fdr, buf, WORDS_LEN)) > 0) { /* read server words is ok */
            printf("server read words : %s\n", buf);
            buf[n] = '\0';
            write(fdw, buf, strlen(buf));    
        }
    }
    
    close(fdw);    
    unlink(FIFO_SVR);
    exit(0);
}


客戶端的例子:


 

/*
 * Fifo client
 *
 */
#include "all.h"



int
main(void)
{
    int fdr, fdw;
    pid_t pid;    
    char clt_path[PATH_LEN] = {'\0'};
    char buf[MAX_LINE] = {'\0'};
    char buf_path[MAX_LINE] = {'\0'};
    
    snprintf(clt_path, PATH_LEN, FIFO_CLT_FMT, (long)getpid());        
    DBG("clt_path1 = ", clt_path);
    snprintf(buf_path, PATH_LEN, "%s\r\n", clt_path);

    if (mkfifo(clt_path, FILE_MODE) == -1 && errno != EEXIST)    
        perr_exit("mkfifo()");

    /* client open clt_path for read
     * open server for write 
       */
    if ((fdw = open(FIFO_SVR, O_WRONLY)) < 0) 
        perr_exit("open()");
    
    /* write my fifo path to server */    
    if (write(fdw, buf_path, PATH_LEN) != PATH_LEN)        
        perr_exit("write()");
    if (write(fdw, WORDS, WORDS_LEN) < 0)    /* write words to fifo server */
        perr_exit("error");

    if ((fdr = open(clt_path, O_RDONLY)) < 0)    
        perr_exit("open()");
    if (read(fdr, buf, WORDS_LEN) > 0) {     /* read reply from fifo server */
        buf[WORDS_LEN] = '\0';
        printf("server said : %s\n", buf);
    }
    
    close(fdr);
    unlink(clt_path);
    
    exit(0);
}

相關文章