操作系統——使用父進程創建四個子進程,在進程間用pipe函數進行通信。(包含程序框圖)


操作系統——使用父進程創建四個子進程,在進程間用pipe函數進行通信(Linux C++)。(包含程序框圖)

1.直接跳轉到Linux端代碼


實驗結果

Linux效果圖(采用UOS + VScode + g++)


image


程序框圖


image


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是在鏈接階段,鏈接這個庫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM