轉自http://z515256164.blog.163.com/blog/static/32443029201211362335184/
在VFS的支援下,使用者態進程讀寫任何類型的檔案系統都可以使用read和write著兩個系統調用,但是在linux核心中沒有這樣的系統調用我們如何操作檔案呢?我們知道read和write在進入核心態之後,實際執行的是sys_read和sys_write,但是查看核心原始碼,發現這些操作檔案的函數都沒有匯出(使用EXPORT_SYMBOL匯出),也就是說在核心模組中是不能使用的,那如何是好?
通過查看sys_open的源碼我們發現,其主要使用了do_filp_open()函數,該函數在fs/namei.c中,而在改檔案中,filp_open函數也是調用了do_filp_open函數,並且介面和sys_open函數極為相似,調用參數也和sys_open一樣,並且使用EXPORT_SYMBOL匯出了,所以我們猜想該函數可以開啟檔案,功能和open一樣。使用同樣的尋找方法,我們找出了一組在核心中操作檔案的函數,如下:
功能 函數原型
開啟檔案 struct file *filp_open(const char *filename, int flags, int mode)
讀取檔案 ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
寫檔案 ssize_t vfs_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
關閉檔案 int filp_close(struct file *filp, fl_owner_t id)
我們注意到在vfs_read和vfs_write函數中,其參數buf指向的使用者空間的記憶體位址,如果我們直接使用核心空間的指標,則會返回-EFALUT。所以我們需要使用
set_fs()和get_fs()宏來改變核心對記憶體位址檢查的處理方式,所以在核心空間對檔案的讀寫流程為:
mm_segment_t fs = get_fs();
set_fs(KERNEL_FS);
//vfs_write();
vfs_read();
set_fs(fs);
下面為一個在核心中對檔案操作的例子:
#include
#include
#include
#include
static char buf[] = "你好";
static char buf1[10];
int __init hello_init(void)
{
struct file *fp;
mm_segment_t fs;
loff_t pos;
printk("hello enter\n");
fp = filp_open("/home/niutao/kernel_file", O_RDWR | O_CREAT, 0644);
if (IS_ERR(fp)) {
printk("create file error\n");
return -1;
}
fs = get_fs();
set_fs(KERNEL_DS);
pos = 0;
vfs_write(fp, buf, sizeof(buf), &pos);
pos = 0;
vfs_read(fp, buf1, sizeof(buf), &pos);
printk("read: %s\n", buf1);
filp_close(fp, NULL);
set_fs(fs);
return 0;
}
void __exit hello_exit(void)
{
printk("hello exit\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");