如何在Linux内核中递归读取目录的内容? [英] How to read contents of a directory recursively in Linux Kernel?

查看:138
本文介绍了如何在Linux内核中递归读取目录的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个树遍历函数,该函数打印给定目录的所有内容 在内核中.我知道如何在用户空间中执行此操作,但我的要求是在内核空间中执行此操作. 为此,我正在研究vfs_readdir函数,并对它的用法有些困惑. 假设我将从其他内核模块调用遍历函数,这意味着请求不会通过用户空间.现在的问题是如何调用vfs_readdir并使用该信息以递归方式解析给定目录.来自vfs_readdir的定义 extern int vfs_readdir(结构文件*,filldir_t,void *);

我可以使用诸如filp_open()之类的函数从文件路径中获取结构文件*,并且据我所知,filldir_t是用于回调函数的函数指针,该函数将填充用户提供的由void *指向的缓冲区.但就我而言,我不需要将任何信息传递回用户.我应该在无效的地方通过什么? 查看filldir函数定义

static int filldir(void * __buf,const char * name,int namlen,loff_t offset,ino_t ino,unsigned int d_type);

此函数的参数从何而来.我的假设是vfs_readdir依次调用诸如file-> f_op_readdir(file,but,filler);之类的东西. 这是否在内部做一些事情并填写参数以调用回调函数? 现在这是一个级别.我应该怎么做才能递归打印给定目录中的所有文件.我想我需要在自己的回调函数中做一些事情,但是我只有一些有关通过此回调函数传递的文件的信息,例如文件名,索引节点号等.使用此信息,我怎么知道它是常规文件还是目录.我的意思是我没有关于文件的dentry或inode数据结构.有什么建议怎么做? 另外,如果要删除回调函数中的文件,是否可以使用索引节点号(即除名称之外在回调函数中具有的编号)来做到这一点?

例如,从 解决方案

vfs_readdir is called, e.g., from readdir syscall implementation. It uses fillonedir as callback, which in turn can easy be understanded: its first argument is just last argument of vfs_readdir, all other arguments(name, namelen, offset, ino, d_type) are copied into user space as is.

Note, that callback for vfs_readdir is executed with inode mutex locked(inode->i_mutex). Probably you shoudn't open subdirectory incide that callback. Instead, save name of the subdirectory somewhere, and open it after vfs_readdir call. This is very similar to the way how you traverse directories tree in the user space.

Note, that since version 3.11 kernel uses another way for iterate entries in directory: iterate_dir. Its second argument combines both callback and callback-specific argument for it, and also include current position in the file. Aside from the first parameter, callback accepts same parameters as before.

As for ino argument, you cannot use it for open given inode(kernel just has no mechanism for open files by inode number). Use filp_open or similar.

这篇关于如何在Linux内核中递归读取目录的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆