应用管道实现父子进程之间的通信
最近在学习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; }