Search code examples
clinuxforkexecmmap

shared memory after exec()


How can I share memory between the parent and the child if the child has run exec() to load another program?

Is it possible using mmap?

By now parent and child share memory properly using mmap, but not after exec is done


Solution

  • You can use shm_open to open a "named" shared memory block which is identified by a file on the filesystem. Example: In the parent:

    int memFd = shm_open("example_memory", O_CREAT | O_RDWR, S_IRWXU);
    if (memFd == -1)
    {
        perror("Can't open file");
        return 1;
    }
    
    int res = ftruncate(memFd, /*size of the memory block you want*/);
    if (res == -1)
    {
        perror("Can't truncate file");
        return res;
    }
    void *buffer = mmap(NULL, /*size of the memory block you want*/, PROT_READ | PROT_WRITE, MAP_SHARED, memFd, 0);
    if (buffer == NULL)
    {
        perror("Can't mmap");
        return -1;
    }
    

    In the other file:

    int memFd = shm_open("example_memory", O_RDONLY, 0);
    if (memFd == -1)
    {
        perror("Can't open file");
        return 1;
    }
    
    void *buffer = mmap(NULL, /*size of the memory block you want*/, PROT_READ, MAP_SHARED, memFd, 0);
    if (buffer == NULL)
    {
        perror("Can't mmap");
        return -1;
    }
    

    After these segments of code you can use buffer to access the shared memory. (Note: it doesn't need to be void*, you can make it a pointer to whatever you intend to store in the shared mem)