在Linux内核中进行文件的读写操作,在一般情况下不推荐这样操作,但在不得已时,也是可以实现的.#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/dcache.h>
#include <linux/fs.h>
#include <linux/err.h>#include <linux/string.h>
#include <linux/errno.h>#include <asm/fcntl.h>
#include <asm/processor.h>
#include <asm/uaccess.h> MODULE_LICENSE("Dual BSD/GPL");
int add_integar(int a,int b)
{
return (a + b);
}int sub_integar(int a,int b)
{
return (a - b);
}EXPORT_SYMBOL(add_integar);
EXPORT_SYMBOL(sub_integar); int init_module(void)
{
int result = 0;
struct task_struct *task = NULL;
char *path = NULL,*ptr = NULL;
char *read_buf = NULL;
struct file* filp = NULL;
mm_segment_t old_fs;
task = current;
read_buf = kmalloc(PAGE_SIZE,GFP_KERNEL);
if (!read_buf)
{
printk("KK Read Buf Alloc Error!
");
return 0;
}
path = kmalloc(PAGE_SIZE,GFP_KERNEL);
if (!path)
{
printk("KK Allocate Error
");
return 0;
} //==================test read write log file=====================
#define MY_FILE "/root/log_file.log"
filp = filp_open(MY_FILE,O_CREAT|O_RDWR,0600); //创建文件
if (filp)
{
old_fs = get_fs();
set_fs(get_ds()); result = filp->f_op->write(filp,read_buf,PAGE_SIZE,&filp->f_pos); //写文件
if (result)
{
printk("New Log Write OK Length:%d
",result);
}
else
{
printk("Write Log File Error
");
} set_fs(old_fs); filp_close(filp,NULL);
}
else
{
printk("Create New Log file failtrue!!
");
}
kfree(read_buf);
read_buf = NULL;
kfree(path);
path = NULL; printk(KERN_INFO"Loading the module ...KK
");
return 0;
}void cleanup_module(void)
{
printk(KERN_INFO"Unloading the module...KK...
"); return ;
}注意的地方:set_fs(get_ds())函数的作用是设置进程能访问的虚拟地址的空间范围。
如果不设置,系统会认为是用户空间,只有3G,所以在内核时,特别是在调用其它的系统调用时,也必须如此,否则,就会出错!