Linux/C/C++将虚拟机磁盘文件挂载到本地文件系统

本文介绍如何在Linux系统中挂载vmdk虚拟机磁盘文件,通过将其转换为raw设备并使用vdfuse库。详细步骤包括分析vmdk文件、转换为raw设备、挂载及卸载过程。同时讨论了挂载多文件系统时的目录结构问题和卸载的稳定性挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vdfmount.h

#ifndef VDFMOUNT_H
#define VDFMOUNT_H

#include <sys/mount.h>
#include "public.h"
#include "WidgetConst.h"
#include "Logger.h"

using namespace LogFile;

class vdfMount
{
   
   
public:
    vdfMount()
    {
   
   
        m_isMount = -1;
        m_imagePath = "";
        m_mapExtType[".vmdk"] = "VMDK";
        m_mapExtType[".vdi"] = "VDI";
        m_mapExtType[".vhd"] = "VHD";
    }
    ~vdfMount();

    /* Added for 虚拟文件系统检查 by chenkun 2020/10/27 below */
    // TODO:注意:逻辑分区不能挂载
    bool CheckVDMount(const string& fPath);
    bool isContainLoop(std::vector<string>& vecDevLoop);
    bool isContainFs(const std::string& str);// 判断某文件系统是否存在
    bool umountAll();
    /* Added for 虚拟文件系统检查 by chenkun 2020/10/27 above */

public:
    int m_isMount;                                   // 挂载状态: -1-未知, 0-已经挂载, 1-未挂载
    std::string m_imagePath;                         // 挂载的镜像文件路径
    std::map<std::string, std::string> m_mapExtType; // 文件后缀-vdfuseType
    std::vector<std::string> m_vecBasicPartition;    // 虚拟机文件挂载点
    std::vector<std::string> m_vecDevLoop;           // loop分区
};

#endif // VDFMOUNT_H

vdfmount.cpp

#include "vdfmount.h"


bool vdfMount::CheckVDMount(const string& fPath)
{
   
   
    if (fPath.empty())
    {
   
   
        return false;
    }
    m_vecBasicPartition.clear();
    m_vecDevLoop.clear();
    string tmpPath = CDir::getFullPath(fPath.c_str());
    // 此函数控制是否挂载成功,不成功则要求客户端重新输入
    // 判断文件是否存在
    if (0 != access(tmpPath.c_str(), F_OK))
    {
   
   
        LOG_INFO("fuse fPath(not found)==%s", fPath.c_str());
        return false;
    }

    // 根据后缀名判断属于哪种虚拟机文件
    // (VDI, VMDK, VHD)
    //fs::path fp = fs::absolute(fs::path(tmpPath));
    //string ext = fp.extension().string();
    std::size_t pos;
    std::string ext;
    if((pos = tmpPath.rfind(".")) != std::string::npos)
    {
   
   
        ext = tmpPath.substr(pos);
    }

    auto iter = m_mapExtType.find(ext);
    if (iter == m_mapExtType.end())
    {
   
   
        LOG_INFO("fuse fPath(type error)==%s", fPath.c_str());
        return false;
    }
    string Type = iter->second;

    // 组合命令产生raw文件
    // ./vdfuse -tVMDK -w -f "/disk3/fd/fd.vmdk" "/tmp/test2"
    if ((false == MKDIR(TmpVDRawPartition.c_str(), false)) ||(false == MKDIR(TmpVDBasicPartition.c_str(), f
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值