我正在用 Rust 编写一个工具,它需要根据当前文件系统是 SSD 还是传统硬盘来改变其功能。
运行时的区别在于,如果文件存在于 SSD 上,则与 HDD 相比,将使用更多线程来访问文件,这只会破坏磁盘并降低性能。
我主要对 Linux 感兴趣,因为这是我的用例,但欢迎任何其他补充。如果可能的话,我还需要以非 root 用户身份执行此操作。是否有系统调用或文件系统设备可以告诉我我所在的设备类型?
最佳答案
信用归@Hackerman :
$ cat /sys/block/sda/queue/rotational
0
如果返回 1,则给定的文件系统位于旋转媒体上。
我已将这个概念充实到一个 shell 脚本中,该脚本可以可靠地确定文件是否位于旋转媒体上:
#!/bin/bash
set -e
# emits the device path to the filesystem where the first argument lives
fs_mount="$(df -h $1 | tail -n 1 | awk '{print $1;}')"
# if it's a symlink, resolve it
if [ -L "$fs_mount" ]; then
fs_mount="$(readlink -f $fs_mount)"
fi
# if it's a device-mapper like LVM or dm-crypt, then we need to be special
if echo $fs_mount | grep -oP '/dev/dm-\d+' >/dev/null ; then
# get the first device slave
first_slave_dev="$(find /sys/block/$(basename $fs_mount)/slaves -mindepth 1 -maxdepth 1 -exec readlink -f {} \; | head -1)"
# actual device
dev="$(cd $first_slave_dev/../ && basename $(pwd))"
else
dev="$(basename $fs_mount | grep -ioP '[a-z]+(?=\d+\b)')"
fi
# now that we have the actual device, we simply ask whether it's rotational or not
if [[ $(cat /sys/block/$dev/queue/rotational) -eq 0 ]]; then
echo "The filesystem hosting $1 is not on an rotational media."
else
echo "The filesystem hosting $1 is on rotational media."
fi
上面的方法对我来说既适用于普通分区(即 /dev/sda1
安装在给定路径),也适用于 dm-crypt
分区(即 /dev/mapper/crypt
安装在给定路径)。我没有用 LVM 测试过它,因为我附近没有 LVM。
对 Bash 不便携表示歉意。
关于linux - 确定是否在 SSD 上的跨平台方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41229644/