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

2 answers

  • answered 2018-01-10 15:31 mdatsev

    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)

  • answered 2018-01-10 15:40 John Bollinger

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

    Neither memory mappings created via mmap() nor POSIX shared-memory segments obtained via shm_open() nor System V shared-memory segments obtained via shmat() are preserved across an exec. That covers all the forms of shared memory I am aware of Linux providing.

    It follows that if you want the child to share memory with the parent after an exec() then the child must (re)connect to the appropriate shared memory after the exec(). Obviously, that means that whatever program is started by the exec() must be written to do that. (Note in particular that on success, the exec-family functions do not return.)

    Is it possible using mmap?

    Only if the child re-maps the memory after the exec().

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

    That is by design.