boost文件内存映射的使用方法
boost_mapping_file.cpp
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
using namespace boost::interprocess;
int main()
{
char file_name[64] = {0};
int count = 1;
int file_size = 1024 * 1024 * 1024 * 1; // GB
for(int i=0; i<count; ++i)
{
sprintf(file_name, "./files/f_%d", i);
boost::interprocess::file_handle_t _handle = ipcdetail::create_or_open_file(file_name, read_write, permissions(),false);
boost::interprocess::ipcdetail::truncate_file(_handle, file_size);
boost::interprocess::ipcdetail::close_file(_handle);
file_mapping *mf = new file_mapping(file_name, read_write);
mapped_region *region = new mapped_region(*mf, read_write);
void *addr = region->get_address();
std::cout << addr << std::endl;
memset(addr, 'h', file_size); // 写入数据,此时占用内存1GB(file_size)
region->flush();
getchar();
_handle=boost::interprocess::ipcdetail::open_existing_file(file_name,read_write,false); // 再次打开文件,写入内容
boost::interprocess::ipcdetail::set_file_pointer(_handle,0,file_end);
std::string data;
data.resize(file_size);
boost::interprocess::ipcdetail::write_file(_handle,data.c_str(),data.size());
boost::interprocess::ipcdetail::close_file(_handle); //关闭,扩容完成
delete region;
delete mf;
getchar();
mf = new file_mapping(file_name, read_write);
region = new mapped_region(*mf, read_write);
addr = region->get_address();
std::cout << addr << std::endl;
memset((char*)addr+file_size, 'o', file_size);
region->flush();
}
getchar();
return 0;
}
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.0.0)
PROJECT(ctest)
SET (MyDeps $ENV{MyDependsGcc})
SET(SUFFIX .so)
MESSAGE(STATUS "MyDepends is at $ENV{MyDependsGcc}")
SET(INCS ${MyDeps}/include)
SET(LNKS ${MyDeps}/lib)
SET(PLATFORM x64)
SET(PREFIX lib)
SET(CMAKE_CXX_STANDARD 17)
INCLUDE_DIRECTORIES(${INCS})
LINK_DIRECTORIES(${LNKS})
LIST(APPEND LIBS
dl
pthread
boost_filesystem
)
ADD_EXECUTABLE(boost_mapping_file boost_mapping_file.cpp)
TARGET_LINK_LIBRARIES(boost_mapping_file ${LIBS})
第一个getchar()之前,内存占用
第二个getchar()之前,内存占用
最后
这篇文章解释不错,可以参考,linux top命令 实存(RES)与虚存(VIRT)详解_top res-CSDN博客