简体   繁体   中英

Boost - mmaping a file into memory for reads&writes

I'm trying to map a region of a particular size into the memory, looking at the docs example: https://www.boost.org/doc/libs/1_70_0/doc/html/interprocess/sharedmemorybetweenprocesses.html#interprocess.sharedmemorybetweenprocesses.mapped_file

as you can notice, boost version is 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);

but an exception occurs: 在此处输入图像描述

I don't need the parent-child functionality, just many threads writing directly to a mmaped region of memory.

Can somebody help me solve this out please? Thank you in advance.

Additional debug info: p is created seemed to be: 在此处输入图像描述

It is also seemed to be that the two following operations did work: 在此处输入图像描述

在此处输入图像描述

Your fbuf doesn't sync. Either sync or limit the scope to get implicit sync on destruction.

#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM