![](/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.