4

Will shared memory allocated in Unix get destroyed automatically if you don't do that ?

e.g one process created that segment, another process take use of it. now they're both crashed for some reason, was that segment causing a memory leak ?

Good Person
  • 1,437
  • 2
  • 23
  • 42
daisy
  • 22,498
  • 29
  • 129
  • 265
  • If both processes close, the memory will probably be reclaimed by the operating system. – Wug Jul 16 '12 at 16:36
  • Assumptions are the root of many bugs. Allocate a huge chunk shared memory, verify using `vmstat` that you can see it allocated, then cause your program to crash. Make sure it's gone. – Eric J. Jul 16 '12 at 16:37
  • Though it looks like, depending on how the memory was allocated, that might not be true. – Wug Jul 16 '12 at 16:38
  • How are you allocating the shared memory block? – Michael Kohne Jul 16 '12 at 16:42

3 Answers3

4

Generally not.

If you're using SysV shared memory (e.g, shm_open), then no. None of the SysV IPC primitives will clean themselves up; you always have to explicitly clean them up, or do so manually with ipcrm. This is one of several reasons that I recommend strongly against using them.

If you're mmapping a file to get shared memory, that file obviously won't go away on its own. Like any other file, you'd have to explicitly unlink it to make it go away. If you've already done that, then you're all set.

  • 1
    To clarify: failing to unlink a mapped file does *not* lock down the allocated memory for all time. Mapped regions can be paged (or swapped) out at any time, and obviously will be if the region is unused by live processes. – Andy Ross Jul 16 '12 at 20:31
1

It depends on the persistence you give the segment. As a rule of thumb, if you give it a name through shm_open (or a key) it will be persistent. As that indicates it will persist after you close the process that created it, unless you somehow "delete" it, that is do an shm_unlink. This is the only way you can share segments between completely different processes.

So if you do that you really have to take care to clean things up. The best strategy for such persistent segments is to have all processes open an file descriptor initially, and then to unlink as soon as everybody is connected. The segment will exist until the last file descriptor to it is closed.

Non-persistent segments can be mapped anonymously directly with mmap. They will go away as your process ceases to exist.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
0

No. Allocated shared memory segments should be discarded explicitly.

Useful command line tools for listing of shred memory segments and removing: ipcs and ipcrm. The last one can be used for ex. for removing a segment when all programs,using it, have crashed.

LiMar
  • 2,822
  • 3
  • 22
  • 28