Forrest Gump
===========================================================
模块中读写文件 与get_fs()
===========================================================
http://www.linuxfans.org/bbs/archiver/tid-42689.html
模块中读写文件

今天在写模块时,犯了一个错误,为了大家别再犯,特记下:

Makefile文件:

DFLAGS = -D __KERNEL__ -D MODULE
CFLAGS = -O2 -g -Wall -Wstrict-prototypes -pipe -I/usr/include/linux/

hello.o:hello.c
gcc -c hello.c $(DFLAGS) $(CFLAGS) -o hello.o

clean:
rm -f *.o *.dat

原文件:hello.c

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/string.h>

#include <asm/fcntl.h>
#include <asm/processor.h>
#include <asm/uaccess.h>

static int count;
static char* string;

MODULE_PARM(count,"i");
MODULE_PARM(string,"s");

int init_module(void)
{
int result;
unsigned long page=0;
struct file* filp=NULL;
mm_segment_t old_fs;

printk("Hello,I am the kernel module. ");

if( !(page=__get_free_page(GFP_KERNEL)) )
{
return -ENOMEM;
}
printk("count=%d. ",count);
filp=filp_open("/usr/huym/module/test.dat",O_CREAT|O_WRONLY,0);
if(!filp)
{
return 0;
}
/*block_write(filp,"write module test. ",19,0);*/
if(filp->f_op && filp->f_op->write)
{
if(string)
{
/*注意的地方*/
old_fs=get_fs();
set_fs(get_ds());
result=filp->f_op->write(filp,string,strlen(string),&filp->f_pos);
if(result<0)
{
printk("write error. ");
}
set_fs(old_fs);
}
}

filp_close(filp,NULL);
printk("string=%s. ",string);

free_page(page);

return 0;
}

void cleanup_module(void)
{
printk("Goodbye. ");
}

命令:

make

insmod hello.o count=2 string="i am write."

删除可:

rmmod hello

make clean
Description by davidfox
set_fs(get_ds())函数的作用是设置进程能访问的虚拟地址的空间范围。
如果不设置,系统会认为是用户空间,只有3G,所以在内核时,特别是
在调用其它的系统调用时,也必须如此,否则,就会出错!!!!!!!
fesir 发表于:2007.07.11 16:14 ::分类: ( Linux/Unix Dev ) ::阅读:(300次) :: 评论 (0)

发表评论
标题

在此添加评论
表情符号: smile laughing tongue angry crying sad wassat wink

称呼

邮箱地址(可选)

个人主页(可选)

 authimage


切换风格
新闻聚合
博客日历
文章归档...
最新发表...
最新评论...
最多阅读文章...
最多评论文章...
博客统计...
Blog信息
网站链接...