簡體   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