ramfs和tmpfs的区别

简介

ramfs和tmpfs是在内存上建立的文件系统(Filesystem)。其优点是读写速度很快,但存在掉电丢失的风险。如果一个进程的性能瓶颈是硬盘的读写,那么可以考虑在ramfs或tmpfs上进行大文件的读写操作。

ramfs和tmpfs之间的区别:

ramfs和tmpfs的区别
特性  tmpfs ramfs
 达到空间上限时继续写入 提示错误信息并终止  可以继续写尚未分配的空间
是否固定大小
 是否使用swap
 具有易失性  是

查看

通过下面的方法可以查看系统中的tmpfs和ramfs:

not@linux-numy:~> mount | grep -E "(tmpfs|ramfs)"
devtmpfs on /dev type devtmpfs (rw,relatime,size=1945280k,nr_inodes=486320,mode=755)
tmpfs on /dev/shm type tmpfs (rw,relatime)
tmpfs on /run type tmpfs (rw,nosuid,nodev,relatime,mode=755)
tmpfs on /sys/fs/cgroup type tmpfs (rw,nosuid,nodev,noexec,mode=755)
tmpfs on /var/lock type tmpfs (rw,nosuid,nodev,relatime,mode=755)
tmpfs on /var/run type tmpfs (rw,nosuid,nodev,relatime,mode=755)

或者:

not@linux-numy:~> df -h | grep -E "(tmpfs|ramfs)"
devtmpfs        1.9G   16K  1.9G   1% /dev
tmpfs           1.9G   27M  1.9G   2% /dev/shm
tmpfs           1.9G  4.3M  1.9G   1% /run
tmpfs           1.9G     0  1.9G   0% /sys/fs/cgroup
tmpfs           1.9G  4.3M  1.9G   1% /var/lock
tmpfs           1.9G  4.3M  1.9G   1% /var/run

我的系统(openSUSE 13.1 "Bottle", kernel version: 3.11.10-21)中,使用的都是tmpfs。我想原因可能是,当存在写溢出时,tmpfs比ramfs更加安全,因为前者会给出错误提示并禁止写操作。

创建

创建tmpfs:

linux-numy:~ # mkdir -p /mnt/tmp
linux-numy:~ # mount -t tmpfs -o size=20m tmpfs /mnt/tmp/
linux-numy:~ # df -h | grep "/mnt/tmp"
tmpfs            20M     0   20M   0% /mnt/tmp

创建ramfs:

linux-numy:~ # mkdir -p /mnt/ram
linux-numy:~ # mount -t ramfs -o size=20m ramfs /mnt/ram/
linux-numy:~ # df -ah | grep "/mnt/ram"
ramfs              0     0     0    - /mnt/ram

这里df只使用h选项是无法显示ramfs的内容的。

df无法显示ramfs信息的原因(无-a选项)

根据superuser.com上的问答《Have I successfully created an ramfs drive?》,Sachin Divekar给出了一段资料引用:

For a ramfs filesystem, the newer kernels report nothing back using "df". There is meant to be a patch for this (to allow for accounting in a ramfs). Philosophically, ramfs is mean to be as simple as possible, apparently, hence the lack of accounting. So data can be stored and used on the ramfs disk, but no accounting of it is possible, other than a loss of memory shown with "free". For this reason the tmpfs is better, since it does keep accounting and "df" shows what's going on.

即,tmpfs会对内存进行accounting(统计内存的使用情况),而ramfs被设计为尽可能的简单,所以不会进行accounting。因此,针对ramfs,在较新的内核中,使用df不会返回ramfs的信息。

参考资料

Overview of RAMFS and TMPFS on Linux

原文地址:https://www.cnblogs.com/dosrun/p/4057112.html