【问题标题】:Boost - mmaping a file into memory for reads&writesBoost - 将文件映射到内存中以进行读写
【发布时间】:2021-12-25 13:08:47
【问题描述】:

我正在尝试将特定大小的区域映射到内存中,查看文档示例: https://www.boost.org/doc/libs/1_70_0/doc/html/interprocess/sharedmemorybetweenprocesses.html#interprocess.sharedmemorybetweenprocesses.mapped_file

如您所见,boost 版本是 1.70.0

    using namespace boost::interprocess;

    const char *FileName  = "c_e_d.bin";
    const std::size_t FileSize = 10000;

    file_mapping::remove(FileName);
    std::filebuf fbuf;
    auto p = fbuf.open(FileName, std::ios_base::in | std::ios_base::out
                        | std::ios_base::trunc | std::ios_base::binary);
    //Set the size
    auto r = fbuf.pubseekoff(FileSize-1, std::ios_base::beg);
    auto r2 = fbuf.sputc(0);

    //Create a file mapping
    file_mapping m_file(FileName, read_write);

    //Map the whole file with read-write permissions in this process
    mapped_region region(m_file, read_write);

但出现异常:

我不需要父子功能,只需要许多线程直接写入映射的内存区域。

有人可以帮我解决这个问题吗? 提前谢谢你。

其他调试信息: p 的创建似乎是:

似乎以下两个操作确实有效:

【问题讨论】:

  • 一个非常常见的错误是假设一切总是正常工作[tm],特别是打开文件总是正常工作,并且没有检查意外的惊喜。
  • 文件已创建,虽然大小为 0,但您是对的,我会检查一下。
  • @SamVarshavchik,还有其他建议或想法吗?
  • 如果没有minimal reproducible example,任何人都可以剪切/粘贴到一个空文件中,然后编译、运行和重现您的问题,那么任何人都不太可能告诉您任何事情。仅仅因为这是程序崩溃或报告错误的地方并不意味着这就是问题所在。 C++ 不能以这种方式工作。问题可能出现在代码中的任何地方,但在出现错误后,程序会继续运行一段时间,然后最终崩溃。这就是为什么 stackoverflow.com 的 help center 要求您显示 minimal reproducible example
  • @SamVarshavchik ,这是一个完整的最小可重现示例,我没有使用 FileSize 参数,但现在我修复了它,所以毫无疑问。

标签: c++ multithreading boost multiprocessing mmap


【解决方案1】:

您的 fbuf 不同步。同步或限制范围以在销毁时获得隐式同步。

#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <fstream>

namespace bip = boost::interprocess;

int main()
{

    const char*       FileName = "c_e_d.bin";
    const std::size_t FileSize = 10000;

    bip::file_mapping::remove(FileName);

    {
        std::filebuf fbuf;
        /*auto         p =*/fbuf.open(FileName,
                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);
        fbuf.pubsync();
    }

    // Create a file mapping
    bip::file_mapping m_file(FileName, bip::read_write);

    // Map the whole file with read-write permissions in this process
    bip::mapped_region region(m_file, bip::read_write);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-28
    相关资源
    最近更新 更多