0
点赞
收藏
分享

微信扫一扫

android命名管道创建使用

凉夜lrs 2022-02-26 阅读 50
androidc++

#创建命名管道

#include <sys/stat.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sstream>
#include <iostream>

#define _SEND_ "/data/user/0/person.wangchen11.xqceditor/files/.ashmem0"
#define _RECV_ "/data/user/0/person.wangchen11.xqceditor/files/.ashmem1"

#define _SIZE_ 100

int createPipe(std::string path){
	
	int ret;
	ret = mkfifo(path.c_str(),S_IFIFO|0666);
	if(ret==0)
	{
		std::cout<<"创建成功\n";
		return 1;
		
	}
	
	std::cout<<"创建失败\n再次创建\n";
	
	char ml[64];
	sprintf(ml,"rm -rf %s",path.c_str());
	system(ml);
	
	ret = mkfifo(path.c_str(),S_IFIFO|0666);
	if(ret==0)
	{
		std::cout<<"创建成功\n";
		return 1;
		
	}
	std::cout<<"创建失败。。。꒦ິ^꒦ິ。。手动创建";
	return 0;
	
}

int main(){
	
	createPipe(_SEND_);
	createPipe(_RECV_);
	
}

#写入管道

#include <sys/stat.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sstream>
#include <iostream>

#define _SEND_ "/data/user/0/person.wangchen11.xqceditor/files/.ashmem0"
#define _RECV_ "/data/user/0/person.wangchen11.xqceditor/files/.ashmem1"

#define _SIZE_ 100

void clearBuff(std::stringstream&sstream){
	sstream.str("");//清空buffer
	sstream.clear();//初始化流
}

FILE*_send;
FILE*_recv;

void send(std::string&str)
{
	if(NULL!=(_send = fopen(_SEND_,"w")))
	{
		fwrite(str.c_str(),1,str.length(),_send);
		fclose(_send);
	}
}

char buffer[_SIZE_];

void recv(std::string&str)
{
	if(NULL!=(_recv = fopen(_RECV_,"r")))
	{
		fread(buffer,1,_SIZE_,_recv);
		str=buffer;
		fclose(_recv);
		memset(buffer,0,_SIZE_);
	}
}

int main()
{
	std::string hello="哈哈😄";
	send(hello);
	
	std::string stop="stop";
	std::string getstop;
	
	recv(getstop);
	
	if(0==stop.compare(getstop))
	   std::cout << "结束运行" ;
}

#读取管道

#include <sys/stat.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sstream>
#include <iostream>

#define _SEND_ "/data/user/0/person.wangchen11.xqceditor/files/.ashmem1"
#define _RECV_ "/data/user/0/person.wangchen11.xqceditor/files/.ashmem0"

#define _SIZE_ 100

void clearBuff(std::stringstream&sstream){
	sstream.str("");//清空buffer
	sstream.clear();//初始化流
}

FILE*_send;
FILE*_recv;

void send(std::string&str)
{
	if(NULL!=(_send = fopen(_SEND_,"w")))
	{
		fwrite(str.c_str(),1,str.length(),_send);
		fclose(_send);
	}
}

char buffer[_SIZE_];

void recv(std::string&str)
{
	if(NULL!=(_recv = fopen(_RECV_,"r")))
	{
		fread(buffer,1,_SIZE_,_recv);
		str=buffer;
		fclose(_recv);
		memset(buffer,0,_SIZE_);
	}
}

int main()
{
	std::string hello;
	recv(hello);
	std::cout << hello;
	
	std::string stop="stop";
	send(stop);
}

##PS:根据以上代码稍作修改,可进行不同应用不同进程之间的高效通讯,类似tcp协议的双项通讯。

举报

相关推荐

0 条评论