代码之家  ›  专栏  ›  技术社区  ›  recipriversexclusion

boost.interprocess中共享内存中的内存问题

  •  1
  • recipriversexclusion  · 技术社区  · 16 年前

    这让我很沮丧。我只是想创建一个共享内存缓冲区类,它在通过boost.interprocess创建的共享内存中使用,我可以在其中读取/存储数据。我写了以下内容来测试功能

    #include <boost/interprocess/shared_memory_object.hpp>
    #include <boost/interprocess/mapped_region.hpp>
    #include <iostream>
    using namespace std;
    using namespace boost::interprocess;
    
    int main( int argc, char* argv[] ) {
        shared_memory_object::remove( "MyName" );
        // Create a shared memory object
        shared_memory_object shm ( create_only, "MyName", read_write );
        // Set size for the shared memory region
        shm.truncate(1000);
        // Map the whole shared memory in this process
        mapped_region region(shm, read_write);
        // Get pointer to the beginning of the mapped shared memory region
        int* start_ptr;
        start_ptr = static_cast<int*>(region.get_address());
    
        // Write data into the buffer
        int* write_ptr = start_ptr;
        for( int i= 0; i<10; i++ ) {
            cout << "Write data: " << i << endl;
            memcpy( write_ptr, &i, sizeof(int) );
            write_ptr++;
        }
    
        // Read data from the buffer
        int* read_ptr = start_ptr;
        int* data;
        for( int i= 0; i<10; i++ ) {
            memcpy( data, read_ptr, sizeof(int) );
            cout << "Read data: " << *data << endl;
            read_ptr++;
        }
    
        shared_memory_object::remove( "MyName" );
        return 0;
    }
    

    当我运行这个程序时,它可以写入数据,但第一个程序会出错。 memcpy 在读取循环中。GDB说:

    程序接收到信号exc_bad_access,无法访问内存。 原因:kern_地址无效:0x0000000000000000 0x0007fffffe007c5在uu memcpy()中

    (GDB)在哪里

    #uuu memcpy()中的0 0x0007fffffe007c5 #1 0x0000000000100000E45 IN MAIN(argc=1,argv=0x7fff5fbff9d0)AT Try.cpp:36

    功能很简单,我不知道我缺少什么。任何帮助都将不胜感激。

    2 回复  |  直到 16 年前
        1
  •  6
  •   please delete me    16 年前

    data 没有被设置为指向任何东西。(确保编译程序时启用了所有警告。)它看起来无论如何都不应该是指针。

    第二个循环可能是:

    int* read_ptr = start_ptr;
    int data;
    for( int i= 0; i<10; i++ ) {
        memcpy( &data, read_ptr, sizeof(int) );
        cout << "Read data: " << data << endl;
        read_ptr++;
    }
    
        2
  •  0
  •   fogo    16 年前

    我不能在这里测试它,因为我没有 boost 有空,但我猜。在这 example , 这个 shared_memory_object 对象首先用于使用标志写入 create_only .

    shared_memory_object shm (create_only, "MySharedMemory", read_write);
    

    然后一秒钟就读出来了 共享内存对象 带有标志的对象 open_only :

    shared_memory_object shm (open_only, "MySharedMemory", read_only);
    

    看来你必须改变你的 共享内存对象 正确的旗帜。