【问题标题】:How to get source device of mount point in Linux programmatically?如何以编程方式在 Linux 中获取挂载点的源设备?
【发布时间】:2019-08-05 04:47:34
【问题描述】:

我想知道某个目录上挂载了哪个设备,像这样:

auto device = get_device_of_mount_point("/path/to/some/dir");
std::cout << device << std::endl; // /dev/sda1

【问题讨论】:

标签: c++ linux posix


【解决方案1】:

这里是一个起点,假设 C++17 可用:

#include <string_view>
#include <fstream>
#include <optional>

std::optional<std::string> get_device_of_mount_point(std::string_view path)
{
   std::ifstream mounts{"/proc/mounts"};
   std::string mountPoint;
   std::string device;

   while (mounts >> device >> mountPoint)
   {
      if (mountPoint == path)
      {
         return device;
      }
   }

   return std::nullopt;
}

您可以按如下方式使用此功能。

if (const auto device = get_device_of_mount_point("/"))
   std::cout << *device << "\n";
else
   std::cout << "Not found\n";

【讨论】:

  • 好的,解决了。但我认为最好的方法是通过 getmntent 解析 /proc/mount。
猜你喜欢
  • 1970-01-01
  • 2014-01-23
  • 2022-11-27
  • 2016-10-19
  • 2010-09-11
  • 2012-06-25
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多