I'm working on a project in C that uses shared memory for IPC on a Linux system. However, I'm a little bit confused about memory management in these segments. I'm using the POSIX API for this project.
I understand how to create the shared segments, and that these persist until a reboot if you fail to properly remove them with
shm_unlink(). Additionally, I understand how to do the actually mapping & unmapping with
munmap respectively. However, the usage of these operations and how it affects the stored data in these shared segments is confusing me.
Here is what I'm trying to properly understand:
Lets say I create a segment using
shm_open() with the
O_CREAT flag. This gives me a file descriptor that I've named
msfd in the below example. Now I have a struct that I map into that address space with the following:
mystruct* ms = (mystruct*)mmap(NULL, sizeof(mystruct), PROT_READ | PROT_WRITE, MAP_SHARED, msfd, 0); //set the elements of the struct here using ms->element = X as usual
Here's where my confusion beings. Lets say that this process is now done accessing that location since it was just setting data for another process to read. Do I still call
I want the other process to still have access to all of this data that the current process has set. Normally, you wouldn't call
free() on a
malloc'ed pointer until its use is no longer needed permanently. However, I understand that when this process exits the unmapping happens automatically anyway. Is the data persisted inside the segment, or does that segment just get reserved with it's allotted size and name?
We're now in the process of the other application that needs to access and read from that shared segment. I understand that we now open that segment with
shm_open() and then perform the same mapping operation with
mmap(). Now we have access to the structure in that segment. When we call
munmap() from this process (NOT the one that created the data) it "unlinks" us from that pointer, however the data is still accessible. Does this assume that process 1 (the creator) has NOT called