如何使用Python代码中创建的共享内存并在Cpp中读取

问题描述 投票:0回答:1

下面是我的python代码,它正在共享内存中写入数据,并且已成功写入

/dev/shm/my_shared_memory

write_data.py

import mmap
import os

# Create a shared memory segment
os.unlink("/dev/shm/my_shared_memory")

shm_fd = os.open("/dev/shm/my_shared_memory", os.O_CREAT | os.O_RDWR, 0o666)
os.ftruncate(shm_fd, 4096)  # Set the size of shared memory

# Memory-map the shared memory segment
shm = mmap.mmap(shm_fd, 4096)

# Write data to shared memory
message = "This is sample data"
shm.write(message.encode())

# Close the shared memory segment
shm.close()
os.close(shm_fd)

下面是读取共享内存的cpp代码。运行后我得到打开共享内存时出错:无效参数

读取共享内存.cpp

#include <iostream>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <cerrno> 
int main() {
    // Open the shared memory segment
    int shm_fd = shm_open("/dev/shm/my_shared_memory", O_RDONLY, 0);
    if (shm_fd == -1) {
        perror("Error opening shared memory");
        return 1;
    }

    // Memory-map the shared memory segment
    void* addr = mmap(NULL, 4096, PROT_READ, MAP_SHARED, shm_fd, 0);
    if (addr == MAP_FAILED) {
        std::cerr << "Error mapping shared memory" << std::endl;
        return 1;
    }

    // Read data from shared memory
    std::string message(static_cast<char*>(addr));

    // Output the message
    std::cout << "Received message from Python: " << message << std::endl;

    // Unmap the shared memory segment
    if (munmap(addr, 4096) == -1) {
        std::cerr << "Error unmapping shared memory" << std::endl;
        return 1;
    }

    // Close the shared memory segment
    if (close(shm_fd) == -1) {
        std::cerr << "Error closing shared memory" << std::endl;
        return 1;
    }

    return 0;
}

我是 cpp 和共享内存的新手,不确定我哪里出错了。

c++ python-3.x shared-memory
1个回答
0
投票

shm_open() 的 EINVAL 表示名称错误。检查 C++ 应用程序是否有权访问该路径,还要检查用户名。

© www.soinside.com 2019 - 2024. All rights reserved.