Search code examples
c++python-3.xshared-memory

How use shared memory created in Python code and reading in Cpp


Below is my python code which is writing data in shared memory and it is successfully writting in /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)

Below is cpp code which is going to read shared memory. after running that I am getting "Error opening shared memory: Invalid argument"

read_shared_memory.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;
}

I am new to cpp and shared memory and not sure where I am getting wrong.


Solution

  • EINVAL for shm_open() means wrong name. Check that the c++ application has access to the path, also check user name.