Reputation: 2061
My program has 2 processes, a master and a slave. The master communicates the slave via a shared memory buffer. The master creates the shared memory with
shm_open("shared_buff", O_CREAT | O_RDWR, 0666);
The slave uses the same shm_open line to gets its pointer into the buff. The master may kill the slave before it has had a chance to gracefully shut down and call shm_unlink() on the shared memory buff. Im wondering if this could cause a memory leak and if so if there is something i can do about it?
I am currently facing a bug where, after the master has killed the slave and attempts to restart it, the slave no longer has access to the buffer. I'm not 100% sure if this is the cause of the issue but seems likely. To be clear everything runs fine on the first pass, its only on the second time the slave is started do issues arise. No errors or stack traces are printed as far as i can tell.
Another solution would be for the newly linked shared mem object (on the slaves end) would simply replace the old allocation. is something like this possible?
Upvotes: 1
Views: 697
Reputation: 1551
If both the master and slave processes open the shared memory using O_CREAT
and one of the processes manages to successfully call shm_unlink
, then the next call to shm_open
will create a new shared memory object, distinct from the first one (a little clause in the shm_unlink
manual page description). I suspect this is what you are seeing on the second time around.
I would suggest that the master process alone be responsible for creating the shared memory object using O_CREAT
and O_EXCL
(and setting up the file size, etc). The slave process should then open the share memory using O_RDWR (or whatever is appropriate) and would then use close
to get rid of the file descriptor (either in a controlled manner or by the kernel when the slave process is killed). All sm_unlink does is remove the name of the shared memory object from the namespace of shared memory object names (just like unlink
simply removes a file name from a directory) and that should be done by the master as part of its graceful (making sure to catch signals appropriately) shutdown.
Upvotes: 1
Reputation: 31467
SysV shared memory is a global, system wide, resource. If you don't release it when you are done with it, eventually you are going to run out.
Upvotes: 0