Discussion:
shm_unlink and munmap
(too old to reply)
pankajtakawale
2009-02-20 16:37:15 UTC
Permalink
I have a question regarding munmap and shm_unlink

Suppose Producer process creates a shared memory, shares a shared mem
key with Consumer process.

Im calling only munmap from Producer.
Consumer calls munmap as well as shm_unlink.

As per shm_unlink man page, shm_unlink removes link and destroys
shared mem region if no process has mapped it.

If Producer unmaps a shared mem region first, and then Consumer unmaps
its shared mem and calls shm_unlink. Its guranteed that shared mem
region will go away from system (shm_unlink would cremove the link and
cleanup shared mem region as well)

Im confused whether following scenario would cleanup shared mem region
from system or not?
Producer creates shared mem
Producer maps it, write data
Consumer opens shared mem
Consumer maps it and reads data
Consumer unmpas shared mem
Consumer unlinks shared mem using shm_unlink [here shm_unlink wont
cleanup shared mem, as it is still being mapped by Producer]
Producer unmaps shared mem

So In above scenario, would shared mem be cleaned from system once
Producer unmaps it? Does munmap destroy shared mem region once it sees
no process has mapped that particular shared mem region?

Pankaj.
pankajtakawale
2009-02-20 18:59:37 UTC
Permalink
Forgot to mention Im using POSIX shared memory apis
ppi
2009-02-23 20:47:39 UTC
Permalink
Post by pankajtakawale
Im confused whether following scenario would cleanup shared mem region
from system or not?
Producer creates shared mem
Producer maps it, write data
Consumer opens shared mem
Consumer maps it and reads data
Consumer unmpas shared mem
Consumer unlinks shared mem using shm_unlink [here shm_unlink wont
cleanup shared mem, as it is still being mapped by Producer]
Producer unmaps shared mem
So In above scenario, would shared mem be cleaned from system once
Producer unmaps it? Does munmap destroy shared mem region once it sees
no process has mapped that particular shared mem region?
yes.

After shm_unlink, the shared memory object cannot be referenced
anymore, and from the os perspective you did remove it.

What is left is the memory mapped in the various processes: as far as
the os is concerned, those are just a bunch of memory pages mapped by
multiple processes (with an ownership count > 0 or whatever name/
counter your os gives it) that will be destroyed (actually recycled
for another purposes) later on.
The last process unmapping those pages just decrements the counter of
these pages to 0 effectively putting those pages back to the list of
free pages.

cheers,
-- paulo

Loading...