如何获得Linux内核中文件的大小? [英] How do you get the size of a file in the linux kernel?

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

问题描述

我找到了此链接( http://www.spinics.net/lists/newbies /msg41016.html ),并一直在考虑这样做.所以我在内核模块中编写了代码:

I found this link (http://www.spinics.net/lists/newbies/msg41016.html) and have been looking into doing just that. So I wrote code in a kernel module:

#include <linux/path.h>
#include <linux/namei.h>
#include <linux/fs.h>

struct path p;
struct kstat ks;
kern_path(filepath, 0, &p);
vfs_getattr(&p, &ks);
printk(KERN_INFO "size: %lld\n", ks.size);

由于以下原因而无法编译:

Which will not compile because:

/root/kernelmodule/hello.c:15: warning: passing argument 1 of ‘vfs_getattr’ from incompatible pointer type
include/linux/fs.h:2563: note: expected ‘struct vfsmount *’ but argument is of type ‘struct path *’
/root/kernelmodule/hello.c:15: warning: passing argument 2 of ‘vfs_getattr’ from incompatible pointer type
include/linux/fs.h:2563: note: expected ‘struct dentry *’ but argument is of type ‘struct kstat *’
/root/kernelmodule/hello.c:15: error: too few arguments to function ‘vfs_getattr’

自从我查看此文档以来,我真的很困惑: http ://lxr.free-electrons.com/source/fs/stat.c#L40

So I am really confused since I was looking at this documentation: http://lxr.free-electrons.com/source/fs/stat.c#L40

现在我在/linux/fs.h中看到vfs_getattr的原型是:

And now I see inside /linux/fs.h that the prototype for vfs_getattr is:

extern int vfs_getattr(struct vfsmount *, struct dentry *, struct kstat *);

有人可以帮助我实施吗?我正在阅读vfsmount和dentry,但仍然迷路.

Can anyone help me with my implementation? I am reading into vfsmount and dentry but am still lost.

推荐答案

对此函数的调用会根据您所使用的内核版本而变化.在3.8和3.9之间引入了两个参数版本.因此,如果您使用的是内核3.8或更低版本,则需要三个参数",而从3.9开始,则需要两个参数.

The call to this function changes depending on which kernel version you are using. The two argument version was introduced somewhere between 3.8 and 3.9. So if you are using kernel 3.8 or before, you need the "three arguments", and 3.9 onwards, you need two arguments.

如果您真的想在内核模式下执行此操作,则在3.9之前的内核上,最好使用

If you really want to do this in kernel mode, on an older kernel than 3.9, you may be better off using the vfs_fstat or vfs_stat

但是,处理内核内部文件的方法却令人生厌,您可能要考虑是否没有更好的选择-例如,如果要将某些文件填充到板子的内存中,在您的系统上,您可以在用户模式进程中加载​​文件,然后通过某些专用的IOCTL类型函数将加载的部分传递到内核中.这是更加内核友好"的,如果您打算将驱动程序/模块包含在整个内核源代码中,则可能需要这样做.

However, dealing with files inside the kernel is frowned upon, and you may want to consider if there isn't a BETTER alternative - for example, if you want to load some file-stuff into the memory of a board that is on your system, you could load the file in a user-mode process, and then pass the loaded parts into the kernel via some private IOCTL type function. This is much more "kernel friendly", and if you are planning on ever trying to get your driver/module included in the overall kernel source code, you probably NEED to do this.

这篇关于如何获得Linux内核中文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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