首页 > 技术文章 > 操作系统——使用管道或者套接字进行通信,编写程序建立四个进程。分别试验三写一读、两写两读情况(包含程序框图)

wsgxg 2021-07-15 14:04 原文

操作系统——使用管道或者套接字进行通信,编写程序建立四个进程。分别试验三写一读、两写两读情况。(包含程序框图)

1.直接跳转到Linux端生产数据代码

2.直接跳转到Linux端读取数据代码


实验结果

Linux效果图(采用UOS + VScode + g++):三写一读


image


程序框图(生产数据)


image


程序框图(读取数据)


image


C++代码(生产数据):

/*生产数据*/
#include <iostream>
#include<cstring>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO_NAME "/tmp/my_fifo"
using namespace std;
int main() {
	int pipe_fd;
	int res;
	// string s="我是子进程"+to_string(getpid())+",^o^!";
	string s;
	cin>>s;
	const char *buf;
	buf=s.c_str();
	//如果管道文件不存在,就创建
	if(access(FIFO_NAME, F_OK)==-1) {
		res = mkfifo( FIFO_NAME, 0777 );
		//创建一个FIFO,如果创建成功,返回值为0
		if(res!=0) {
			cout<<"没能成功创建FIFO:"<<FIFO_NAME<<endl;
			exit( EXIT_FAILURE );
			//表示异常退出
		}
	}
	cout<<"进程:"<<getpid()<<" 打开FIFO管道:"<<FIFO_NAME<<endl;
	pipe_fd = open( FIFO_NAME, O_WRONLY );
	//以只写方式打开
	if(pipe_fd==-1 ) {
		cout<<"打开失败\n";
		exit( EXIT_FAILURE );
		//打开失败,异常退出
	} else {
		res=write( pipe_fd, buf, 30 );
		if(res==-1 ) {
			cout<<"写失败\n";
			exit( EXIT_FAILURE );
		}
		close( pipe_fd );
	}
	cout<<"进程:"<<getpid()<<" 写结束 写入的内容为:"<<buf<<endl;
	exit( EXIT_SUCCESS );
	//成功退出
}
//g++ test531.cpp -o test531&&./test531

C++代码(读取数据):

/*读取数据*/
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FIFO_NAME "/tmp/my_fifo"
using namespace std;
int main() {
	int pipe_fd;
	int res;
	char buf[30];
	cout<<"进程:"<<getpid()<<" 打开FIFO管道:"<<FIFO_NAME<<endl;
	pipe_fd = open( FIFO_NAME,O_RDONLY );
	//以只读方式打开
	if(pipe_fd==-1) {
		cout<<"打开失败\n";
		exit( EXIT_FAILURE );
		//异常退出
	} else {
		res = read( pipe_fd, buf, 30);
		if( -1 == res ) {
			cout<<"读失败\n";
			exit( EXIT_FAILURE );
			//异常退出
		}
		close( pipe_fd );
	}
	cout<<"进程:"<<getpid()<<" 读结束 读出的内容为:"<<buf<<endl;
	exit( EXIT_SUCCESS );
	//成功退出
}
//g++ test53.cpp -o test53&&./test53

推荐阅读