我正在用Rust编写一个工具,它需要根据当前文件系统是SSD还是传统硬盘来改变其功能。
运行时的不同之处在于,如果文件存在于SSD上,将使用更多的线程来访问文件,而不是HDD,这只会震动磁盘并降低性能。
我主要对Linux感兴趣,因为这是我的用例,但欢迎任何其他补充。如果可能的话,我还需要以非root用户的身份执行此操作。有没有系统调用或文件系统设备可以告诉我我在哪种类型的设备上?
发布于 2016-12-20 04:08:03
功劳归于@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不能移植。
https://stackoverflow.com/questions/41229644
复制相似问题