應用管道實現父子進程之間的通訊

來源:互聯網
上載者:User
應用管道實現父子進程之間的通訊最近在學習Linux/Unix的IPC,而通過管道是其中的一種方式。管道的限制在與,它只能實現父子進程間的通訊,通常我們通常會建立一個管道,然後fork出一個子進程,在父進程關掉讀端(fd[0]),在子進程裡關掉寫端(fd[1]),然後在父進程的寫端(fd[1])寫入資料,在子進程中的讀端(fd[0])讀資料,這樣就實現了父子進程間的通訊。
實現代碼如下:
#include <iostream>#include "apue.h"#include "err_msg.h"using namespace std;void print(const char * str){int pid = getpid();cout << str << endl;cout << "pid = " << pid << endl;}int main(){int n;int fd[2];pid_t pid;char line[MAXLINE];cout << "MAXLINE = " << MAXLINE << endl;if (pipe(fd) < 0){err_sys("pipe error");}if ((pid = fork()) < 0){err_sys("fork error");}else if (pid > 0)   /*parent process*/{close(fd[0]);while (1) {cout << "--------------------------------" << endl;print((char *)"parent process");cout << "write the data to pipe" << endl;write(fd[1], "hello world\n", 12);cout << "--------------------------------" << endl;sleep(10);}}else /*child process*/{close(fd[1]);while (1) {print((char *)"child process");cout << "read the data from pipe" << endl;n = read(fd[0], line, MAXLINE);write(STDOUT_FILENO, line, n);sleep(15);}}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.