應用管道實現父子進程之間的通訊最近在學習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;}