'Relationship between shared memory and files
Ignoring some details there are two low-level SHM APIs available for in Linux.
We have the older (e.g System V IPC vs POSIX IPC) SysV interface using:
- ftok
- shmctl
- shmget
- shmat
- shmdt
and the newer Posix interface (though Posix seems to standardize the SysV one as well):
- shm_open
- shm_unlink
When using shm_open() there appears to be a clear 1 to 1 mapping between files and shared memory segments. However if you use shmget() you can relate multiple segments to a single path using, for example:
key1=ftok(path,1);
key2=ftok(path,2);
shmget(key1,...)
shmget(key2,...)
What if anything the relationship between files and segments in this case? The path given to ftok is just a placeholder. I can't see what purpose it serves. If we consider the Unix philosophy as everything is a file why is this not a one to one mapping?
Separate but related question:
- Should the SysV interface be considered deprecated?
There is no such suggestion in shm_open or shm_get
I can find only vague suggestions like:
- https://www.unix.com/linux/53491-shmat-failure-while-using-large-amount-shared-memory.html
- https://stackoverflow.com/a/35666695/1569204
I think the SysV is considered less thread-safe.
Is there any reason why you might prefer the SysV one (or the posix one) in a modern application?
Solution 1:[1]
The path given to ftok is just a placeholder in the "everything is a file" tradition.
After some time considering I would say mmap is a simpler, safer and more effective API. I personally would avoid shmget etc. completely if possible.
It is particularly awkward to clean up after shmget() see:
See also:
- Linux shared memory: shmget() vs mmap()?
- System V IPC vs POSIX IPC
- How do you correctly cleanup and re-use SysV shared memory segments?
An argument used in favour of system-v in one of the linked questions is that Posix was less widely implemented. I don't know if that was true then but it seems even less likely to be true now. Given the dominance of GNU/Linux & BSD derivatives. Even the legendarily 'unique' AIX claims Posix compliance these days.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bruce Adams |