![](/img/trans.png)
[英]In Linux in C/C++ how to determine filesystem type of a mounted or unmounted partition
[英]Getting the name of the last mounted/unmounted filesystem
实现的解决方案涉及udev , poll , setmntent和getmntent 。
这个想法是保留所有已挂载文件系统的列表(由于设备数量通常很少,因此不会占用大量内存),并且该列表只需创建一次即可。
在“ / proc / mounts”上使用poll()可以发现文件系统何时被挂载或卸载。 然后,使用udev可以获取当时安装的设备列表。 因此,您可以将其与已经拥有的列表进行比较,这样您将知道文件系统是已安装还是已卸载,以及哪个文件系统受到了影响。
获取已安装节点的功能。
vector<string> get_mounted_storage_nodes()
{
vector<string> storage_nodes = get_storage_nodes(); // This uses udev.
vector<string> mounted_nodes;
struct mntent *mntent;
FILE *file;
file = setmntent("/etc/mtab", "r");
while ((mntent = getmntent(file)))
{
string mounted_node(mntent->mnt_fsname);
vector<string>::iterator it;
it = find(storage_nodes.begin(), storage_nodes.end(), mounted_node);
if (it != storage_nodes.end())
mounted_nodes.push_back(mounted_node);
}
return mounted_nodes;
}
只需比较两个灯的大小即可。
// event is a convenience struct that holds the name of the affected
// filesystem and the action (mounted or unmounted).
vector<string> new_mounted_nodes = get_mounted_storage_nodes();
int new_size = new_mounted_nodes.size();
int curr_size = mounted_nodes.size();
if (new_size == curr_size)
event.action = NONE; // No partition was mount or unmounted.
// This case is very common when the poll
// is working as non-blocking because the timeout.
else
event.action = new_size > curr_size ? MOUNT : UMOUNT;
vector<string> new_mounted_nodes = get_mounted_storage_nodes();
使用上一行,如果已挂载文件系统,则只需要查找new_mounted nodes
的元素,该元素不在您已经拥有的已挂载节点的列表中。 另一方面,如果文件系统已卸载,则必须在列表中找到已存在但在new_mounted_nodes
没有的new_mounted_nodes
。
代码示例:
switch(event.action)
{
case MOUNT:
for (auto it = new_mounted_nodes.begin(); it != new_mounted_nodes.end(); ++it)
if (find(mounted_nodes.begin(), mounted_nodes.end(), *it) == mounted_nodes.end())
{
event.node = *it;
break;
}
break;
case UMOUNT:
for (auto it = mounted_nodes.begin(); it != mounted_nodes.end(); ++it)
if (find(new_mounted_nodes.begin(), new_mounted_nodes.end(), *it) == new_mounted_nodes.end())
{
event.node = *it;
break;
}
break;
default:
break;
}
重要说明:最新代码的复杂度为O(n ^ 2) ,但已安装设备的数量通常(我不想绝对)小于20。因此,该算法将运行得非常快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.