Car*_*Way 6 linux cache linux-kernel tmpfs
AFAIK,Linux 有一个页面缓存来提高性能(例如,如果你打开一个文件,linux 将该文件缓存在 RAM 中),然后如果再次请求文件并缓存它,操作系统会避免从磁盘读取文件并从缓存...
我的问题是:如果您在tmpfs 中有一个文件并且您与该文件交互(读取),该文件是否会在 RAM 中重复(一个在 tmpfs 中,另一个在页面缓存中?)
tmpfs 是否使用 Linux 页面缓存?
tmpfs 和页面缓存是同一枚硬币的两个方面。
如https://www.kernel.org/doc/Documentation/filesystems/tmpfs.txt 中所述(强调我的)
tmpfs 将所有内容放入内核内部缓存,并通过增大和缩小来容纳它包含的文件,并且能够将不需要的页面交换到交换空间。
[...]
由于tmpfs 完全存在于页面缓存和交换中,所有 tmpfs 页面将在 /proc/meminfo 中显示为“Shmem”,在 free(1) 中显示为“Shared”。
因此,复制此缓存将是非常出乎意料的。它已经在缓存中,tmpfs 只是缓存系统的前端。
我的问题是:如果您在 tmpfs 中有一个文件并且您与该文件交互(读取),该文件是否会在 RAM 中重复(一个在 tmpfs 中,另一个在页面缓存中?)
这可以通过实验确定。
# sync
# echo 3 > /proc/sys/vm/drop_caches
# free -m
total used free shared buff/cache available
Mem: 15940 2005 13331 264 603 13390
Swap: 0 0 0
Run Code Online (Sandbox Code Playgroud)
所以,我碰巧有大约 13000 个可用内存,并且没有进程运行会改变它太剧烈,也没有交换。让我们在 tmpfs 上烧掉 ~6000:
# mount -t tmpfs -o size=6000M none /mnt/tmp
# dd if=/dev/urandom of=/mnt/tmp/big.file
dd: writing to '/mnt/tmp/big.file': No space left on device
6291456000 bytes (6.3 GB, 5.9 GiB) copied
Run Code Online (Sandbox Code Playgroud)
所以 tmpfs 充满了随机数据。现在有什么免费的?
# free -m
total used free shared buff/cache available
Mem: 15940 1958 7347 6269 6633 7429
Swap: 0 0 0
Run Code Online (Sandbox Code Playgroud)
于是free
下楼从13331到7347,而shared
与buff/cache
这两个上升6000。这很有趣,但它仍然只能算作一个,想这就是为什么他们称之为共享-.-”
故意读取文件:
# cat /mnt/tmp/big.file > /dev/null
# free -m
total used free shared buff/cache available
Mem: 15940 2055 7237 6269 6647 7332
Swap: 0 0 0
Run Code Online (Sandbox Code Playgroud)
计数没有上升(反正不是 6000 的数量级)。
刻意读点别的:
# cat /some/other/file > /dev/null
# free -m
total used free shared buff/cache available
Mem: 15940 2011 157 6303 13771 7334
Swap: 0 0 0
Run Code Online (Sandbox Code Playgroud)
...现在free
下降到 157,缓存几乎满了。
所以,总结一下:tmpfs 本身已经代表了页面缓存。在 tmpfs 中读取文件时,它们不再被页面缓存复制。