繁体   English   中英

如何从linux内核中的目录中获取文件列表?

[英]How to get a file list from a directory inside the linux kernel?

我刚刚看到在任何 rootfs 之前有一个 ROOT /目录(无论是来自 initrd 还是形成磁盘)
我已经知道它确实包含/root/dev并安装了 devtmpfs (如果选择了CONFIG_DEVTMPFS_MOUNT

但是我无法找到是否还有其他目录以及它们是哪些。

所以关键是在init/do_mounts.c的第 403 行之前插入代码,以便将列表init/do_mounts.c到屏幕上。
问题是我不知道如何使用 struct direent 来获取旧readdir()的目录列表int readdir(unsigned int fd, struct dirent *dirp, unsigned int count);

您可以使用filp_open()从内核空间打开文件。
您要使用iterate_dir()函数。
您必须定义一个struct dir_context(include / linux / fs.h)并提供某种filldir函数(例如,将条目添加到列表中)。

我无法找到任何其他示例来执行此操作,因此这是我的代码:

typedef int (*readdir_t)(void *, const char *, int, loff_t, u64, unsigned);

#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0))
struct callback_context {
    struct dir_context ctx;
    readdir_t filler;
    void* context;
};

int iterate_dir_callback(struct dir_context *ctx, const char *name, int namlen,
        loff_t offset, u64 ino, unsigned int d_type)
{
    struct callback_context *buf = container_of(ctx, struct callback_context, ctx);
    return buf->filler(buf->context, name, namlen, offset, ino, d_type);
}
#endif


int readdir(const char* path, readdir_t filler, void* context)
{
    int res;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0))
    struct callback_context buf = {
        .ctx.actor = (filldir_t)iterate_dir_callback,
        .context = context,
        .filler = filler
    };
#endif

    struct file* dir  = filp_open(path, O_DIRECTORY, S_IRWXU | S_IRWXG | S_IRWXO);
    if(!IS_ERR(dir))
    {

#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0))
        res = iterate_dir(dir, &buf.ctx);
#else
        res = vfs_readdir(dir, filler, context);
#endif
        filp_close(dir, NULL);
    } 
    else res = (int)PTR_ERR(dir);
    return res;
}

要使用它,请定义您的回调并调用 readdir:

int filldir_callback(void* data, const char *name, int namlen,
        loff_t offset, u64 ino, unsigned int d_type)
{
    printk(KERN_NOTICE "file: %.*s type: %d\n", namlen, name, d_type);
    if(d_type == DT_DIR) ; // do sth with your subdirs
    return 0;
}

readdir("/etc", filldir_callback, (void*)123);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM