Linux Pipe (進程間通信,生產者消費者)

PIPE是Linux下可以用來實現進程間通信的一種手段,當我們調用pipe系統調用時,將會產生一對文件描述符,fd[0]可以用來讀,fd[1]用來寫,fd[1]寫的數據將會在fd[0]中讀到,我們稱之爲管道。進程之間可以依賴管道的方式實現進程間通信,pipe是半雙工的,所以如果要實現pipe之間互相通信的話,需要建立2對pipe。下面我們演示用pipe實現父進程生產數字,子進程消費數字並排序的一個程序。

#include <iostream>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <sys/types.h>
#include <sys/wait.h>

#define END_FLAG (1 << (sizeof(int)*8 - 1))

using namespace std;

enum PIPE_FD_TYPE {
    PIPE_READ = 0,
    PIPE_WRITE
};

int main() {
    int pipe_fd[2] = {-1, -1};
    if(pipe(pipe_fd) != 0) {
        exit(0);
    }
    int pid = -1;
    if((pid = fork()) == -1) {
        exit(0);
    }

    //child
    if(pid == 0) {
        cout<<"child start\n";
        int data = -1;
        vector<int> v;
        while(read(pipe_fd[PIPE_READ], &data, sizeof(data)) > 0) {
            if(data == END_FLAG) {
                break;
            }
            v.push_back(data);
        }
        cout<<"size : "<<v.size()<<endl;
        sort(v.begin(), v.end());
        for(auto i : v) {
            cout<<i<<" ";
        }
        cout<<endl;
        cout<<"child end\n";
    }

    //parent
    if(pid != 0) {
        cout<<"parent start\n";
        int v[] = {134, 123, 1111, -1, 0, 888, 7564, 976, 9876, 66, 99, 123, 189};
        for(int i = 0; i < sizeof(v)/sizeof(v[0]); i++) {
            write(pipe_fd[PIPE_WRITE], &v[i], sizeof(v[i]));
        }
        int end = END_FLAG;
        write(pipe_fd[PIPE_WRITE], &end, sizeof(end));
        int status = -1;
        waitpid(-1, &status, 0);//等待子進程結束
        cout<<"paranet end\n";
    }
    return 0;
}
發佈了44 篇原創文章 · 獲贊 7 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章