c++ - 在 boost.interprocess 中从共享内存进行 memcpy 的问题

标签 c++ shared-memory boost-interprocess

这让我沮丧得发疯。我只是想创建一个共享内存缓冲区类,该类在通过 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 表示如下:

Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000 0x00007fffffe007c5 in __memcpy ()

(gdb) where

#0 0x00007fffffe007c5 in __memcpy () #1 0x0000000100000e45 in main (argc=1, argv=0x7fff5fbff9d0) at try.cpp:36

功能非常简单,我不知道我错过了什么。任何帮助将不胜感激。

最佳答案

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++;
}

关于c++ - 在 boost.interprocess 中从共享内存进行 memcpy 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2373526/

相关文章:

c++ - C++ 中的 'operator auto' 是什么?

c++ - 字符到类型的非 constexpr 转换

c++ - 在 C++ 中取消链接与删除

c - 涉及多个进程的矩阵乘法中的共享内存

c++ - 是否可以通过共享内存从不同进程更新 Eigen3 或其他矩阵库 2D 矩阵?

c++ - boost::interprocess::managed_shared_memory: Grow(): 内存重用?

c++ - 理解c++中的库函数

c - 对于 sleep() 同步父进程和子进程之间的传输,我有什么选择?

c++ - 使用内存映射文件进行持久化 - 是否需要 volatile?

c++ - boost::interprocess::map - 如何使用 basic_string 作为类型更新值