[英]What is the lifetime of shared memory on Linux
I am creating, writing to and reading from a shared segment on Linux using the ftok/shmget/shmat/shmdt functions. 我使用ftok / shmget / shmat / shmdt函数在Linux上创建,写入和读取共享段。
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. 我原本预计,当共享一个段的最后一个进程执行shmdt时,该段将是空闲的。
Can I rely on this behavior? 我可以依靠这种行为吗? Or is it analogous to continuing to use a pointer after free()'ing it?
或者它类似于在free()之后继续使用指针?
The shared memory area remains until it is deleted via shmctl(shmid,IPC_RMID,...)
[or system reboot]. 共享内存区域保持不变,直到通过
shmctl(shmid,IPC_RMID,...)
[或系统重启]删除它。 This will take effect after every process has done shmdt
[or terminated]. 这将在每个进程完成
shmdt
[或终止]后生效。
The semantics are very similar to a file. 语义与文件非常相似。
shmat
is like open
. shmat
就像open
一样。 shmdt
is like close
and the [above] shmctl
is like unlink
. shmdt
就像close
,[上面] shmctl
就像unlink
。
If you close a file, you'd like it to persist until specifically deleted, wouldn't you? 如果你关闭一个文件,你会希望它一直存在,直到被特别删除,不是吗? So, shared memory segments operate similarly
因此,共享内存段的运行方式类似
shmdt
only detaches you memory, no erase/overwrite is performed on the data segment. shmdt
只会分离内存,不会对数据段执行擦除/覆盖。 Until some other process maps and uses it again data will persevere. 在某些其他流程映射并再次使用它之前,数据将持续存在。
Also, you should use newer, POSIX compliant mmap
. 此外,您应该使用更新的,符合POSIX标准的
mmap
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.