#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>

static charbuf[] ="hello";
static charbuf1[10];

int __init hello_init(void)
{
struct file *fp;
mm_segment_t fs;
loff_t pos;

fp = filp_open("/home/ming/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");

我試了在我的機器上可以讀到,你可以試試,這樣的確破壞對system call的封裝。樓上已經說了,再說幾句吧,一般bootloader我們會從硬碟載入。內核這樣做是繞過了系統調用,我為啥沒有直接調用sys_open之類,因為內核沒有導出那個符號,所以我調用了 filp_open類似的,然後還要幹掉內核對地址空間的檢查,因為你的buf不可能允許在內核空間,這樣非常hacking,不建議在工程里使用。


推薦閱讀:
相关文章