IPC通信概述

一、管道通信

 管道是一种半双工的通信方式,具有固定的读端和写端,而且只支持有血缘关系的进程之间通信。因为管道是只存在于内存中,并不属于任何的系统文件。

  头文件:#include <unistd.h>

  函数原型:int pipe(int pipefd[2]);

  函数参数:fd[0]代表读端,fd[1]代表写端

  函数详解:一旦建立一个管道,就会创建并打开两个文件描述符,当fork出子进程后,也会复制两份相同的文件描述符,这样就可以实现父子进程间的通信。

例子:用pipe实现ps aux |grep bash的命令,并输出到屏幕上

 1 #include <iostream>
 2 #include <unistd.h>
 3 #include <sys/types.h>
 4 #include <sys/wait.h>
 5 
 6 using namespace std;
 7 int main(int argc, char *argv[])
 8 {
 9     int fd[2];
10     if(pipe(fd) < 0)  // 创建一个管道
11     {
12         cout << "open pipe error" << endl;
13         return -1;
14     }
15     pid_t pid = fork(); // 创建一个子进程
16     if(pid < 0)
17     {
18         cout << "create process failed" << endl;
19     }
20     if(pid == 0)
21     {
22         close(fd[0]);
23         dup2(fd[1], STDOUT_FILENO);  // 将标准输出 重定向到 写端
24         execlp("ps", "ps", "aux", NULL);
25     }
26     else
27     {
28         close(fd[1]);
29         dup2(fd[0], STDIN_FILENO);  // 将标准输入重定向到读端
30         execlp("grep", "grep", "bash", NULL); 
31         wait(NULL);
32     }
33     
34     return 0;
35 }

猜你喜欢

转载自www.cnblogs.com/zz1314/p/12890429.html