title: Do I need to use shm_unlink on a shared memory object?
body: <p>I've written a server (GNU C++ / Linux) which runs continuously, and occasionally executes small stand-alone programs to do work. In order to efficiently get data to the worker programs, the server creates and maps a shared memory object (code abbreviated for clarity): </p>
  
  <pre><code>int fd = shm_open("/shm_file", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
  ftruncate(...);
  data = mmap(...);
  // etc...
  launchWorker(...);   // Start the worker program
  </code></pre>
  
  <p>The worker program then opens this shared memory in a similar way (except read-only, without the O_CREAT and O_TRUNC, i.e. we assume it already exists). </p>
  
  <p>When the worker finishes, it closes the file descriptor, unmaps with munmap(...) and unlinks with shm_unlink(...). </p>
  
  <p>At this point, there is a file "/dev/shm/shm_file" which I guess is the shared memory object. Unlinking in the worker doesn't remove it because the server still has it open.  When the server unlinks it, the file system object disappears. This behavior is consistent with the man page for shm_open / shm_unlink, and works fine for my server/worker case. </p>
  
  <p>However, now I'd like the workers to be able to share certain data between themselves, and possibly (for testing) do this when the server is not running. </p>
  
  <p>If I create a shared memory object in one worker program and DO NOT use munmap(...) and shm_unlink(...) when it exits, I note that the shared memory object remains in /dev/shm, and I can open it again in another worker program. This is handy. </p>
  
  <p>However, is it safe to do this? (i.e. repeatedly run a program which maps shared memory, then doesn't unmap/unlink it)? I'm guessing that the unmap() doesn't matter as the memory mapping will vanish with the process, but what about the shm_unlink? Given that the OS decided when to delete the object based on whether it is still being used, if I fail to call shm_unlink() every time, will this cause a leak of some kind? </p>