【问题标题】:How to map a path to the corresponding /dev file in UNIX - C++?如何将路径映射到 UNIX - C++ 中相应的 /dev 文件?
【发布时间】:2012-06-06 08:44:12
【问题描述】:

我正在尝试获取给定路径名的相应 /dev 文件,有点像 df 命令

我目前使用此命令,但我宁愿不使用system() 函数或系统特定命令。

这是当前代码:

const string PathStr (Path); // Path is input value

// get the /dev/* files
string Cmd ("df 2> /dev/null | grep /dev | awk '{print $1, $6}'");

FILE * Pipe = popen (Cmd.c_str(), "r");
if (!Pipe)
{
    errorLog("Cannot execute command : \"" + Cmd + '"');
    return string();
}

char Buf [BufSz];
stringstream sstr;
while (!feof(Pipe))
{
    if (fgets(Buf, BufSz, Pipe))
        sstr << Buf;
}
pclose(Pipe);

// get the actual /dev file
pair<string, string> DiskPaths;
while (!sstr.eof())
{
    string Dev, MountPoint;
    sstr >> Dev >> MountPoint;
    if (string::npos != PathStr.find(MountPoint) &&
        MountPoint.size() > DiskPaths.second.size())
        DiskPaths = make_pair(Dev, MountPoint);
}

【问题讨论】:

    标签: c++ unix path device


    【解决方案1】:

    调用system() 并解析输出可能是更可靠、更便携的方式来做你想做的事情,因为df 命令可能使用各种系统相关的技巧来将设备编号解析为名称在/dev 中,否则您必须自己实现。

    您可以轻松获取文件所在文件系统的设备编号:它是stat() 结构的st_dev 字段。但是,如何在/dev 中找到与该编号对应的文件留作df 命令的练习。特别要记住,并不是每个文件系统都是从/dev 中的文件挂载的:想想NFS,以及像/proc 这样的特殊文件系统。

    以下是您可以做的其他一些事情:

    • 扫描/dev 中的每个文件,寻找st_rdev 相同编号的块设备
    • 解析已安装文件系统的表(/etc/mtab 或 /etc/mnttab,它取决于系统),寻找看起来可能是您感兴趣的路径名的父目录的安装前缀。

    【讨论】:

    • 对,stat() 技巧似乎可以解决问题,但继续使用df 会简单得多。因此,df 也读取了/etc/mtab 文件,但我想这比自己做要可靠得多。
    猜你喜欢
    • 2022-12-10
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2015-07-03
    相关资源
    最近更新 更多