首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将文件加进内存进行读写。

将文件加进内存进行读写。
EN

Stack Overflow用户
提问于 2021-12-25 13:08:47
回答 1查看 86关注 0票数 0

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

正如您注意到的,boost版本是1.70.0

代码语言:javascript
运行
复制
    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);

但有一个例外情况:

我不需要父-子功能,只是许多线程直接写到内存的mmaped区域。

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

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

以下两项行动似乎也起了作用:

EN

回答 1

Stack Overflow用户

发布于 2021-12-25 21:54:55

你的fbuf不同步。同步或限制作用域以在销毁时获得隐式同步。

代码语言:javascript
运行
复制
#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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70480239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档