【问题标题】:Get all mount points in kernel module获取内核模块中的所有挂载点
【发布时间】:2017-10-07 00:08:46
【问题描述】:

我正在尝试获取内核模块中的所有挂载点。下面是我想出的。由于strcat,它会出现段错误。这是获取挂载点的正确方法吗?这行得通吗?如果是这样,我该如何修复段错误?如果没有,如何在 linux 内核模块中获取挂载点?

我尝试过cycle the whole namespace looking for mountpoint roots that match,但它是从 2003 年开始的,内核发生了很大变化,所以它基本上没用。还尝试了get filesystem mount point in kernel module,但它又是从 2012 年开始的,所以它已经过时了。

static int __init misc_init(void)
{
    struct path path;
    struct dentry *thedentry;
    struct dentry *curdentry;

    kern_path("/", LOOKUP_FOLLOW, &path);
    thedentry = path.dentry;
    list_for_each_entry(curdentry, &thedentry->d_subdirs, d_child)
    {
        kern_path(strncat("/", curdentry->d_name.name, strlen(curdentry->d_name.name)), LOOKUP_FOLLOW, &path);
        if (path_is_mountpoint(&path))
        {
            printk("%s: is a mountpoint", curdentry->d_name.name);
        }
        else
            printk("%s: is not a mountpoint", curdentry->d_name.name);
    }
    return 0;
}

【问题讨论】:

  • 你读过man strncat吗?你会感到惊讶。
  • 是的,我有。我试过 strjoin、strlcat、strncat、strcat。
  • ... 而strlen(curdentry->d_name.name)), 也毫无意义
  • 那么你知道你的strncat有什么问题吗?提示:第一个参数应该是什么?
  • 修复了仍然坏的问题。

标签: c linux linux-kernel kernel-module


【解决方案1】:

dentry 结构中有它的标志。 d_flags。并且有一个标志 DCACHED_MOUNTED。获取当前指针。那里的 fs_struct。然后是根。这为您提供了当前文件系统的根目录。从那里循环遍历所有子目录,如果 d_flags & DCACHE_MOUNTED 通过,那么它就是一个挂载点。

ssize_t read_proc(struct file *filp, char *buf, size_t len, loff_t *offp )
{
    struct dentry *curdentry;

    list_for_each_entry(curdentry, &current->fs->root.mnt->mnt_root->d_subdirs, d_child)
    {
        if ( curdentry->d_flags & DCACHE_MOUNTED)
            printk("%s is mounted", curdentry->d_name.name);
    }
    return 0;
}

【讨论】:

  • 我用它来列出给定dentry的所有条目,它只打印一个名字但至少有4个(不包括.和..)你知道哪里错了吗?
  • 如果你复制粘贴的代码,那么它只会打印挂载的目录名,如果你想要所有目录,取出 if 并打印 curdentry->d_name.name
【解决方案2】:

以下可能是获取所有挂载点而不检查系统所有条目的更佳方式。

struct mnt_namespace *ns = current->nsproxy->mnt_ns;
struct mount *mnt;

list_for_each_entry(mnt, &ns->list, mnt_list) {
...do something with each mnt...
}

请注意,此代码不包含namespace_sem,因此无法保证遍历 mnt_list 的结果。但是,恕我直言,它的正确性至少不亚于遍历所有不带挂载锁的dentries。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2014-04-24
    • 2012-03-14
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多