Boost::interprocess_library_error异常创建shared_memory_object

boost::interprocess_library_error exception when creating shared_memory_object

本文关键字:memory shared object 创建 error interprocess library Boost 异常      更新时间:2023-10-16

在某些罕见的情况下(实际上是在单个客户端的计算机上),下面的代码会抛出一个异常"library_error":

namespace ipc = boost::interprocess;
ipc::shared_memory_object m_shm;
...
bool initAsServer(size_t sharedMemSize)
{
    ipc::permissions perm;
    perm.set_unrestricted();
    try
    {
        m_shm = ipc::shared_memory_object(
            ipc::create_only,
            CNameGenHelper::genUniqueNameUtf8().c_str(), // static std::string genUniqueNameUtf8()
            ipc::read_write, perm);
    }
    catch(const ipc::interprocess_exception& ex)
    {
        logError("failed with exception "%s"", ex.what());
        return false;
    }
    ...
}

日志文件:[ERR] failed with exception "boost::interprocess_exception::library_error"

Boost v1.58,平台win32, vs13.


如果你能帮我解决这个问题,我将非常感激。提前感谢!

问题原因是Windows "System"日志中事件ID =" 6005"且源名称为"EventLog"的事件。事件查看器- Windows日志-系统。如果系统日志不包含至少一个这样的事件,那么方法boost::interprocess::winapi::get_last_bootup_time()返回falseboost::interprocess::ipcdetail::windows_bootstamp构造器抛出异常。(定义BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME).

因此,似乎清除"System"windows事件日志就足够了,任何使用Boost共享内存的应用程序都将停止工作。

多么糟糕的逻辑:使用windows事件日志的内容。似乎这个boost ipc实现的bug还没有被修复(boost_1_61_0)。

我对这种情况的临时解决方案(不重启计算机):

bool fixBoostIpcSharedMem6005issue() const
{
    bool result = false;
    HANDLE hEventLog = ::RegisterEventSourceA(NULL, "EventLog");
    if(hEventLog)
    {
        const char* msg = "simple boost shared memory fix for 6005";
        if(::ReportEventA(hEventLog, EVENTLOG_INFORMATION_TYPE, 0, 6005, NULL, 1, 0, &msg, NULL))
            result = true;
        ::DeregisterEventSource(hEventLog);
    }
    return result;
}

使用它并尝试再次使用ipc::shared_memory_object:)

关于这个问题的许多详细解释,由库的作者之一:Boost进程间:在Windows上获得启动时间是不可靠的,这里:在Windows上使用事件日志的进程间get_last_bootup_time是完全不可靠的

显然,一个可靠的解决方案是将预处理器常量BOOST_INTERPROCESS_SHARED_DIR_PATH定义为函数调用,该函数在机器启动后总是以字符串形式返回相同的目录路径。例如,通过格式化文件的更新时间戳,在启动时写入。

您可以#定义BOOST_INTERPROCESS_BOOTSTAMP_IS_SESSION_MANAGER_BASED或BOOST_INTERPROCESS_BOOTSTAMP_IS_LASTBOOTUPTIME来切换到基于注册表或WMI的启动时间检测。或者,您可以使用BOOST_INTERPROCESS_SHARED_DIR_PATH,但它在Windows上有点没用,因为它使用硬编码的路径。BOOST_INTERPROCESS_SHARED_DIR_FUNC是更好的选择,因为它允许您定义返回共享目录路径的函数。