操作系统——使用父进程创建四个子进程,在进程间用pipe函数进行通信(Linux C++)。(包含程序框图)
实验结果
Linux效果图(采用UOS + VScode + g++)

程序框图

C++代码:
#include <iostream>
#include<cstring>
#include<sys/types.h>
#include <unistd.h>
using namespace std;
int main(void)
{
const char *buf;
int pdf[4][2];
int i=0;
while(i<4){
if(pipe(pdf[i])==-1)
cout<<"pipe 失败!";
i++;
}
int pid[4];
if(!fork()){
close(pdf[0][0]);//关闭读端
string s="我是子进程"+to_string(getpid())+",^o^!";
buf=s.c_str();
write(pdf[0][1],buf,30);
cout<<"子进程"<<getpid()<<"写入管道1"<<endl;
}else if(!fork()){
close(pdf[1][0]);//关闭读端
string s="我是子进程"+to_string(getpid())+",^o^!";
buf=s.c_str();
write(pdf[1][1],buf,30);
cout<<"子进程"<<getpid()<<"写入管道2"<<endl;
}else if(!fork()){
close(pdf[2][0]);//关闭读端
string s="我是子进程"+to_string(getpid())+",^o^!";
buf=s.c_str();
write(pdf[2][1],buf,30);
cout<<"子进程"<<getpid()<<"写入管道3"<<endl;
}else if(!fork()){
close(pdf[3][0]);//关闭读端
string s="我是子进程"+to_string(getpid())+",^o^!";
buf=s.c_str();
write(pdf[3][1],buf,30);
cout<<"子进程"<<getpid()<<"写入管道4"<<endl;
}else{
char buf[30];
int i=0;
while(i<4){
close(pdf[i][1]);//关闭写端
//父进程读数据
if(read(pdf[i][0],buf,30)==-1){
cout<<"写失败\n";
exit( EXIT_FAILURE );
}
cout<<"读管道"<<i+1<<":"<<buf<<endl;
i++;
}
}
return 0;
}
//g++ test51.cpp -o test51 -lpthread&&./test51
//加上-lpthread是在链接阶段,链接这个库