• 首页

  • 官方

  • 主题

  • 关注

  • 联系

操作系统——使用FIFO函数进行通信,由进程A生产数据,由进程B读取数据。(包含程序框图)

操作系统——使用FIFO函数进行通信,由进程A生产数据,由进程B读取数据。(包含程序框图)

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^!";
	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++ test52.cpp -o test52&&./test52

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++ test521.cpp -o test521&&./test521
posted @ 2021-07-15 13:57  戈小戈  阅读(705)  评论(0编辑  收藏  举报