I’m working on a project where I must open a directory and read the files/directories inside at kernel level. I’m basically trying to find out how ls is implemented at kernel level.
Right now I’ve figured out how to get a file descriptor for a directory using sys_open() and the O_DIRECTORY flag, but I don’t know how to read the fd that I receive. If anyone has any tips or other suggestions I’d appreciate it. (Keep in mind this has to be done at kernel level).
Edit:For a long story short, For a school project I am implementing file/directory attributes. Where I’m storring the attributes is a hidden folder at the same level of the file with a given attribute. (So a file in Desktop/MyFolder has an attributes folder called Desktop/MyFolder/.filename_attr). Trust me I don’t care to mess around in kernel for funsies. But the reason I need to read a dir at kernel level is because it’s apart of project specs.
To add to caf’s answer mentioning
vfs_readdir(), reading and writing to files from within the kernel is is considered unsafe (except for/proc, which acts as an interface to internal data structures in the kernel.)The reasons are well described in this linuxjournal article, although they also provide a hack to access files. I don’t think their method could be easily modified to work for directories. A more correct approach is accessing the kernel’s filesystem inode entries, which is what
vfs_readdirdoes.Notice that
vfs_readdir()expects afile *parameter. To obtain afilestructure pointer from a user space file descriptor, you should utilize the kernel’s file descriptor table.The kernel.org files documentation says the following on doing so safely:
Finally, take a look at
filldir_t, the second parameter type.