一、如何使用boost创建共享内存
Boost提供了一个封装共享内存映射的类shared_memory_object,这个类可以用来从映射文件创建映射区域。使用时需要包含头文件
#include <boost/interprocess/shared_memory_object.hpp>
1. 创建共享内存
shared_memory_object shdmem(open_or_create, //指定共享内存是要创建或打开(共享内存如果存在就打开,否则创建之)
"shared_memory", //共享内存的名称
read_write); //访问共享内存的模式
Boost提供了三种访问共享内存的方式
create_only:以指定的访问模式创建共享内存文件,如果文件已经存在,则会抛出异常
open_only:以指定的访问模式打开共享内存文件,如果文件不存在,则会抛出异常
open_or_create:以指定访问模式尝试创建共享内存文件,如果文件存在,它会以指定模式打开它,创建或者打开失败会抛出异常
//!Creates a shared memory object with name "name" and mode "mode", with the access mode "mode"
//!If the file previously exists, throws an error.*/
shared_memory_object(create_only_t, const char *name, mode_t mode, const permissions &perm = permissions())
{ this->priv_open_or_create(ipcdetail::DoCreate, name, mode, perm); }
//!Tries to create a shared memory object with name "name" and mode "mode", with the
//!access mode "mode". If the file previously exists, it tries to open it with mode "mode".
//!Otherwise throws an error.
shared_memory_object(open_or_create_t, const char *name, mode_t mode, const permissions &perm = permissions())
{ this->priv_open_or_create(ipcdetail::DoOpenOrCreate, name, mode, perm); }
//!Tries to open a shared memory object with name "name", with the access mode "mode".
//!If the file does not previously exist, it throws an error.
shared_memory_object(open_only_t, const char *name, mode_t mode)
{ this->priv_open_or_create(ipcdetail::DoOpen, name, mode, permissions()); }