I am using the combination of shm_open()
and mmap()
to create a shared memory segment for IPC. What I'm wondering is how the backing files (in /dev/shm
in my system, Linux kernel 2.6.31) are cleaned up.
My questions are threefold:
1) Is it the process's responsibility to unlink the files upon termination? If so, what if the process dies before it unlinks them?
2) Since I suspect the answer to #1 is "yes, it's the program's responsibility", is it considered "good practice" for my program to remove any stale files it notices before creating a new one, in case previous instances died uncleanly?
3) Is there a way to ask the kernel to remove the backing file after the last process unmaps the memory? I am thinking of something similar to shmctl(id, IPC_RMID, ...)
in SysV sty开发者_如何学Gole shared memory.
The answers are as following:
Yes, it is the program's responsibility, although it may be possible to ensure cleanup, see my answer to 3.
You could remove the stale files, You could also just use the existing shared memory object (which I assume you were going to recreate anyway).
If you know that no other users for the shared section will exist after it is initially created, you can use
shm_unlink
right after mapping your shared memory. The memory region will be deallocated once all users unmap (and close) it.
精彩评论