设为首页 加入收藏

TOP

Linux内核模块读写文件
2014-11-24 07:48:45 来源: 作者: 【 】 浏览:0
Tags:Linux 内核 模块 读写 文件

在Linux内核中进行文件的读写操作,在一般情况下


不推荐这样操作,但在不得已时,也是可以实现的.


#include
#include
#include
#include
#include
#include


#include
#include


#include
#include
#include



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!\r\n");
return 0;
}
path = kmalloc(PAGE_SIZE,GFP_KERNEL);
if (!path)
{
printk("KK Allocate Error\r\n");
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 \n",result);
}
else
{
printk("Write Log File Error \n");
}


set_fs(old_fs);


filp_close(filp,NULL);
}
else
{
printk("Create New Log file failtrue!!\n");
}



kfree(read_buf);
read_buf = NULL;
kfree(path);
path = NULL;


printk(KERN_INFO"Loading the module ...KK\n");
return 0;
}


void cleanup_module(void)
{
printk(KERN_INFO"Unloading the module...KK...\n");


return ;
}


注意的地方:


set_fs(get_ds())函数的作用是设置进程能访问的虚拟地址的空间范围。
如果不设置,系统会认为是用户空间,只有3G,所以在内核时,特别是在调用其它的系统调用时,也必须如此,否则,就会出错!


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UT6410 Linux 2.6.24 YAFFS2做根.. 下一篇GNU/Linux下Java开发环境的安装和..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·JAVA现在的就业环境 (2025-12-26 01:19:24)
·最好的java反编译工 (2025-12-26 01:19:21)
·预测一下2025年Java (2025-12-26 01:19:19)
·Libevent C++ 高并发 (2025-12-26 00:49:30)
·C++ dll 设计接口时 (2025-12-26 00:49:28)