两个类就搞定了。file_mapping mapped_region
但当映射的region和文件大小一样时,当文件大于1g时 产生异常,
此时只能分段映射文件才能避免以上问题。
region的粒度由获得 std::size_t page_size = mapped_region::get_page_size();
2:向region中写入数据,读出数据
时应小心
如下面的实例中/**NOTIC*/部分
示例:
// testboostmapregion.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <cstddef>
#include <cstdlib>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
using namespace boost::interprocess;
file_mapping::remove("e:\\output\\strucRegionfile.bin");
const std::size_t FileSize = 1000 * mapped_region::get_page_size();
{ //Create a file
std::filebuf fbuf;
fbuf.open("e:\\output\\strucRegionfile.bin", std::ios_base::in | std::ios_base::out
| std::ios_base::trunc | std::ios_base::binary);
//Set the size
fbuf.pubseekoff(FileSize-1, std::ios_base::beg);
fbuf.sputc(0);
}
//Remove file on exit
struct file_remove
{
~file_remove (){ file_mapping::remove("e:\\output\\strucRegionfile.bin"); }
} destroy_on_exit;
struct item{
double d1;
int n1;
float f1;
} ;
//Create a file mapping
file_mapping m_file("e:\\output\\strucRegionfile.bin", read_write);
//Map the whole file with read-write permissions in this process
try{
mapped_region region(m_file, read_write);//,10,10000000);
//Get the address of the mapped region
void* addr = region.get_address();/*notic*/
std::size_t size = region.get_size();
//Write all the memory to 1
std::memset(addr, 0, size);
//int sizeitem = sizeof(item);
char* _items = (char*)addr;
item it;
it.d1 =9.8;
it.f1 =7.3;
it.n1 =3;
cout<<"in: d1: "<<it.d1<<" f1: "<<it.f1<<" n1:"<<it.n1<<endl;
//*((item*)(addr+size-sizeof(item)))
*((item*)(_items+size-sizeof(item))) =it;//ok/*notic*/
//memcpy(addr+size - sizeof(item),&it,sizeof(item));//ok/*notic*/
item out = *((item*)(_items+size-sizeof(item)));//ok/*notic*/
//memcpy(&out,addr+size - sizeof(item),sizeof(item));//ok/*notic*/
cout<<"out: d1: "<<out.d1<<"f1: "<<out.f1<<" n1:"<<out.n1<<endl;
}
catch( boost::interprocess::interprocess_exception& ex ){
cout << "\n mapped_region exception.what:" << ex.what() << endl;
}
//Launch child process
//std::string s(argv[0]); s += " child ";
// if(0 != std::system(s.c_str()))
m_file.remove("e:\\output\\file.bin");
return 0;
}