什么是进程间通信
指在操作系统中,多个进程之间交换数据或信息的机制。由于不同进程的内存空间是相互独立的,因此它们无法直接访问彼此的内存。这就需要通过某些机制来实现进程之间的信息交换,以便协作完成任务。
从内存角度:
在操作系统中,每个进程都有自己独立的虚拟内存空间,这意味着一个进程不能直接访问另一个进程的内存数据。因此,进程间通信机制必须通过操作系统提供的中介或内存区域来实现数据交换。
管道实现进程间通信
管道不是进程的资源,而是操作系统的资源,所以不是fork的复制对象。
管道创建方式
#include<unistd.h>
int pipe(int filedes[2])
其中filedes[0]是管道接收数据的文件描述符(管道出口),filedes[1]是发送数据的文件描述符(管道入口)。
#include<unistd.h>
#include<iostream>
using namespace std;
int main()
{
int fds[2];
int res=pipe(fds);
if(res==-1)
{
perror("pipe create error");
}
int pid=fork();
char buff[]="hello pipe";
char buffs[30];
if(pid==0)
{
write(fds[1],buff,sizeof(buff));
}
else{
read(fds[0],buffs,1024);
cout<<buffs<<endl;
}
}
以上为pipe管道单向通信。
下面为两个进程通过一个管道实现双向通信的例子
#include<unistd.h>
#include<iostream>
using namespace std;
int main()
{
int fds[2];
int res=pipe(fds);
if(res==-1)
{
perror("pipe create error");
}
int pid=fork();
char buff1[]="hello pipe";
char buff2[]="hello pipe222";
char buffs[30];
if(pid==0)
{
write(fds[1],buff1,sizeof(buff1));
sleep(2); //sleep两秒,否则子进程会自己读走管道中的内容
read(fds[0],buffs,1024);
cout<<buffs<<endl;
}
else{
read(fds[0],buffs,1024);
cout<<buffs<<endl;
write(fds[1],buff2,sizeof(buff2));
sleep(3);
}
}
其实质还是单工通信,因为在同一时刻管道只能支持从一段到另一端,若想真正实现双工,还需创建两个管道。