Why use shm_open? Why use shm_open? linux linux

Why use shm_open?


If you open and mmap() a regular file, data will end up in that file.

If you just need to share a memory region, without the need to persist the data, which incurs extra I/O overhead, use shm_open().

Such a memory region would also allow you to store other kinds of objects such as mutexes or semaphores, which you can't store in a mmap()'ed regular file on most systems.


Both calls are essentially equivalent on modern Linux - 1st approach could be used to access POSIX shared memory from languages like go (see https://github.com/fabiokung/shm/blob/master/shm_linux.go) where POSIX shared memory not natively available - it might be different for other OS/version where 1st call would lead to some file creation or /dev/shm just not available and/or possibly slower performance. Rules of path merging might also be evolving from version to version of librt

1st approach called memory mapped files API (supported in std libs)

2nd called POSIX shared memory API (requires librt aka libposix on Linux as dependence It's internally constructs path and calls open)


After reading the source of shm_open, I can say those two methods are almost the same.

link: https://code.woboq.org/userspace/glibc/sysdeps/posix/shm_open.c.html

shm_open just adds shm_dir prefix then invokes normal open syscall, nothing special.