正在设置由boost创建的共享内存的权限

Setting permission for shared memory created by boost

本文关键字:共享 内存 权限 创建 boost 设置      更新时间:2023-10-16

我们打开了一个由另一个进程(如)创建的boost共享内存

  boost::interprocess::managed_shared_memory segment(boost::interprocess::open_only, "SharedMem");

但是,如果创建共享内存的进程是根用户,那么读取它的进程(如果是普通用户)将失败,原因如下:

terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
what():  Permission denied

我该怎么做才能避免这种情况?就是允许所有人共享内存?

如果查看shared_memory构造函数,它会获取一个权限对象。boost::interprocess::permissions::set_unrestricted可能就是您想要的

void set_unrestricted();
//Sets permissions to unrestricted access:
//        A null DACL for windows or 0666 for UNIX.

据此,它被添加到1.45版本

下面是一个示例代码片段,用于在创建期间授予共享内存不受限制的权限

boost::interprocess::permissions  unrestricted_permissions;
unrestricted_permissions.set_unrestricted();
shared_mem = new managed_shared_memory(open_or_create, name.c_str(), size, 0, unrestricted_permissions);