5

I am creating, writing to and reading from a shared segment on Linux using the ftok/shmget/shmat/shmdt functions.

If I write to the segment in one program which then exits, and subsequently read the segment from another program later, I am surprised to find the data still there.

I would have expected that when the last process sharing a segment does a shmdt, the segment would be free'd.

Can I rely on this behavior? Or is it analogous to continuing to use a pointer after free()'ing it?

user69374
  • 541
  • 1
  • 5
  • 13
  • Freeing the segment and replacing the data are two different thing. Freeing doesn't necessarily means the old data has been replaced. Until the segment is over-written by some other process it will have the data it initially had but to other programs it is garbage. – usamazf Feb 27 '16 at 06:29
  • Detaching (shmdt) does not destroy a shared memory segment. To do so you will need to do a shmctl() specifying IPC_RMID as "cmd". But note the man page (on Linux) indicates that the shared memory segment ID will not be destroyed until all processes have detached (shmdt) from it. – TonyB Feb 27 '16 at 06:41

2 Answers2

4

The shared memory area remains until it is deleted via shmctl(shmid,IPC_RMID,...) [or system reboot]. This will take effect after every process has done shmdt [or terminated].

The semantics are very similar to a file. shmat is like open. shmdt is like close and the [above] shmctl is like unlink.

If you close a file, you'd like it to persist until specifically deleted, wouldn't you? So, shared memory segments operate similarly

Craig Estey
  • 30,627
  • 4
  • 24
  • 48
0

shmdt only detaches you memory, no erase/overwrite is performed on the data segment. Until some other process maps and uses it again data will persevere.

Also, you should use newer, POSIX compliant mmap.

Peter Silon
  • 457
  • 2
  • 11
  • 1
    Shared memory segments have at least kernel lifetime, and in general they disappeared at reboot. That means that you have to remove them explicitly (IPC_RMID operation of semctl). You can think of them as *temporary files*. – Jean-Baptiste Yunès Feb 27 '16 at 13:18