簡體   English   中英

獲取最后一個已掛載/未掛載文件系統的名稱

[英]Getting the name of the last mounted/unmounted filesystem

我知道我可以監視(使用輪詢選擇 )上的文件/proc/mount/etc/mtab和findout 文件系統被安裝或卸載。 我也可以使用getmntent獲取已掛載文件系統的列表。

我的應用旨在監視已掛載的文件系統並報告任何更改(已安裝或已卸載)。

我的解決方案:

  1. 檢測/proc/mounts某些更改。
  2. 使用getmntent獲取當前所有已掛載的文件系統。
  3. 將獲得的列表與先前的列表進行比較。
  4. 處理差異。

但是我需要知道從/proc/mounts/etc/mtab輪詢時是否有某種方法可以掛載最后一個文件系統。 只需讀取文件或將數據輪詢為某種結構(例如mntent )。

解決方案說明

實現的解決方案涉及udevpollsetmntentgetmntent

這個想法是保留所有已掛載文件系統的列表(由於設備數量通常很少,因此不會占用大量內存),並且該列表只需創建一次即可。

“ / 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM