2013-09-23 58 views
2

我發現這個鏈接(http://www.spinics.net/lists/newbies/msg41016.html),並一直在考慮這樣做。如何獲得Linux內核中文件的大小?

#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); 

這將不能編譯,因爲::所以我一個內核模塊中編寫代碼

/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

現在我在/linux/fs.h裏面看到,vfs_getattr的原型是:

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

任何人都可以幫我實施我的嗎?我正在閱讀vfsmount和dentry,但仍然丟失。

+1

「in the linux kernel」 - 意思是說你正在編寫kernel-land代碼?如果不是,那麼只需'stat()'或'ftell()'。 – 2013-09-23 18:18:28

+1

是的,這是在一個內核模塊中。 – wright8191

回答

3

對此功能的調用會根據所使用的內核版本而變化。這兩個參數版本介於3.8到3.9之間。因此,如果您使用的是內核3.8或之前的版本,則需要「三個參數」和3.9以上的版本,您需要兩個參數。

如果你真的想這樣做,在內核模式下,比3.9內核比較老,你可能會更好使用vfs_fstatvfs_stat

然而,處理內核中的文件是不可取的,而你可能要考慮是否沒有更好的選擇 - 例如,如果要將某些文件加載​​到系統中的電路板的內存中,則可以在用戶模式過程中加載文件,以及然後通過一些私有的IOCTL類型函數將加載的部分傳遞給內核。這更「內核友好」,如果你計劃試圖讓你的驅動程序/模塊包含在整個內核源代碼中,那麼你可能需要這樣做。

+0

謝謝你的迴應。你是如何獲得文件描述符傳遞給vfs_fstat的? @MatsPetersson – wright8191

+0

也許打開文件?這是傳統上的做法......;) –