`shm_open` 使用什么类型的内存对象?

What type of memory objects does `shm_open` use?

通常,共享内存是使用映射到进程地址空间的部分磁盘文件实现的。每当在共享区域上发生内存访问时,文件系统都会参与将更改写入磁盘,这是一个很大的开销。

通常,调用 fopen() returns 传递给 mmap() 的文件描述符以创建文件的内存映射。 shm_open,显然,以同样的方式工作。它 returns 一个文件描述符,甚至可以用于常规文件操作(例如 ftruncateftellfseek ...等)。我们确实将字符串指定为 shm_open 的参数,但与 fopen() 不同的是,它不是可见文件系统(安装的 HDD、闪存驱动器、SSD 等)上的真实文件的名称。完全不相关的进程可以使用相同的字符串名称将相同的区域映射到它们的地址空间。

那么,传递给 shm_open 的字符串参数是什么以及 shm_open creates/opens 是什么?它是某个临时文件系统 (/tmp) 上的一个文件,它最终被许多进程用来创建共享区域(好吧,我认为它必须是某种文件,因为它 returns 是一个文件描述符)?或者它是由内核支持的某种神秘且隐藏的文件系统?

人们说 shm_openfopen 快,因为不涉及磁盘操作所以我建议的理论是内核使用不可见的基于 RAM 的文件系统来实现与 shm_open 的共享内存!

Usually, shared memory is implemented using portions of On-Disk files mapped to processes address spaces.

这通常是错误的,至少在台式机或笔记本电脑上如此 运行 最近的 Linux 发行版,具有合理数量的 RAM(例如至少 8GB)。

所以,磁盘是不相关的。您可以使用 shm_open 而无需任何交换。参见 shm_overview(7), and notice that /dev/shm/ is generally a tmpfs mounted file system so don't use any disk. See tmpfs(5). And tmpfs don't use the disk (unless you reach thrashing conditions, which is unlikely) since it works in virtual memory

the filesystem is involved to write changes on the disk which is a great overhead.

这通常是错误的。在大多数系统上,最近写入的文件位于 page cache, which does not reach the disk quickly (BTW, that is why the shutdown procedure needs to call sync(2) 中,否则很少使用...)。

顺便说一句,在大多数台式机和笔记本电脑上,很容易观察到。硬盘有一些LED,在使用shm_open和相关调用时不会看到它闪烁。顺便说一句,你也可以使用 proc(5) (特别是 /proc/diskstats 等....)来查询内核关于它的磁盘 activity.

Usually, shared memory is implemented using portions of On-Disk files mapped to processes address spaces. Whenever a memory access occurs on the shared region, the filesystem is involved to write changes on the disk which is a great overhead.

这似乎很冒昧,也不完全正确。基本上所有实现共享内存区域(在 IPC 意义上)的机器都具有支持该功能的虚拟内存单元。可能有也可能没有任何持久存储支持任何特定的共享内存段或其任何部分。只有被调出的部分(如果有的话)需要由此类存储支持。

shm_open, apparently, works in the same way. It returns a file descriptor which can even be used with regular file operations (e.g ftruncate, ftell, fseek ...etc).

shm_open() 有一个以 open() 为模型的接口,并且它 returns 一个可以有意义地用于某些通用目的的文件描述符 I/O功能,不要在任何更广泛的意义上暗示 shm_open() "works in the same way"。几乎所有的系统资源都以文件的形式呈现给进程。这提供了一个更简单的整体系统接口,但它并不意味着底层资源的任何共性,除了它们可以通过相同的功能进行操作——在它们确实可以的范围内。

So, what is the string parameter passed to shm_open & what does shm_open creates/opens ?

参数是标识共享内存段的字符串。您已经知道这一点,但您似乎认为不仅如此。没有,至少在指定 shm_open 接口的级别 (POSIX) 中没有。标识符主要对内核有意义。不同的实现以不同的方式处理细节。

Is it a file on some temporary filesystem (/tmp) which is eventually used by many processes to create the shared region

可能是,但可能不是。为它提供的任何文件系统接口都可能(但不确定)是一个虚拟文件系统,而不是磁盘上实际的、可访问的文件。持久存储(如果使用的话)很可能由系统的交换 space.

提供

(Well, i think it has to be some kind of files since it returns a file descriptor) ?

这样的结论是没有根据的。套接字和管道也通过文件描述符表示,但它们没有相应的可访问文件。

Or is it some kind of a mysterious and hidden filesystem backed by the kernel ?

这可能是一个更好的概念,但同样,可能根本没有任何持久存储。然而,就存在而言,它很可能是系统交换的一部分space,这并不那么神秘。