如何为/ tmp目录使用RAM存储以及如何为其设置最大RAM使用量?

看到匿名关于问题的评论后如何清理/ tmp目录? ,我发现在我的系统上实现是一个好主意,因为我有16GB的RAM而且我从未使用过它。

我的临时文件永远不会写入磁盘。 它们被写入RAM磁盘。 我确实在/ etc / fstab中放了tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0

我的问题是:

我可以为/tmp RAM使用设置最大值吗? 在这种情况下,如果超过最大数量会发生什么,它会写入硬盘驱动器吗?

我读过一个解决方案,其中说明:

 mkdir -p /tmp/ram sudo mount -t tmpfs -o size=512M tmpfs /tmp/ram/ 

但据我了解,这不是一个永久的解决方案。 如果我需要它是永久性的,则必须将其添加到/etc/fstab配置文件中。

如果这是正确的解决方案,我如何将该mount命令转换为/etc/fstab的一行?

你是绝对正确的。 相应的fstab条目如下所示:

 tmpfs /tmp tmpfs defaults,noatime,nosuid,nodev,noexec,mode=1777,size=512M 0 0 

请注意:

随着tmpfs被填满,它将通过提供“空间不足”错误来表现为任何物理硬盘驱动器。 虽然重新启动(并因此清空缓存)将解决这个问题,但是当单个操作开始消耗更多空间而不是tmpfs上的空间时,可能会遇到麻烦。 在这种情况下,您的计算机将开始从ram切换到磁盘,这将使您的系统爬行停止,当然,假设您有一个交换分区。

考虑到这一点,现在512MB的尺寸可能要小得多,因为在现代机器中存在更多的RAM并且它变得便宜得多。 既然你已经有了16GB的ram,那么使用tmpfs的一半你的ram的默认值应该足以满足几乎所有的场景。 要使用默认值,只需在/etc/fstab文件中省略size=512M条目即可。

另一个说明:

您也可以轻松地将其他系统文件夹安装到ramdisk中,例如

/var/cache

/var/games

/var/log/apt (仅使用defaults,noatime without mode=nosuid

但要注意:同样的规则适用于上述,空间不足可能会造成重大麻烦。 例如,想象/ / var / log / apt的空间不足会导致无法安装任何程序! 此外,将/var/log文件夹加载到ramdisk将在重新启动时删除所有日志文件,因此如果发生任何意外情况,您将无法调试系统。 因此,使用这些设置需要您自担风险!

编者注:我删除了tmpfs挂载选项中的/run ,因为默认情况下此文件夹及其子文件夹已经安装在tmpfs

在使用systemd系统上,您可以选择使用systemd单元文件而不是fstab来实现使用tmpfs挂载tmp的目标。 在我的Ubuntu 16.04系统上,我跑了:

 sudo cp /usr/share/systemd/tmp.mount /etc/systemd/system/tmp.mount sudo systemctl enable tmp.mount sudo systemctl start tmp.mount 

文件/usr/share/systemd/tmp.mount看起来像:

 # This file is part of systemd. # # systemd is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. [Unit] Description=Temporary Directory Documentation=man:hier(7) Documentation=http://www.freedesktop.org/wiki/Software/systemd/APIFileSystems ConditionPathIsSymbolicLink=!/tmp DefaultDependencies=no Conflicts=umount.target Before=local-fs.target umount.target After=swap.target [Mount] What=tmpfs Where=/tmp Type=tmpfs Options=mode=1777,strictatime [Install] WantedBy=local-fs.target 

使用FuzzyQ的fstab方法,systemd动态地将您的fstab条目转换为装载单元。 我认为这两种方法都不会更好。