模块中读写文件 与get_fs()

http://www.linuxfans.org/bbs/archiver/tid-42689.html[@more@]
模块中读写文件

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

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,所以在内核时,特别是
在调用其它的系统调用时,也必须如此,否则,就会出错!!!!!!!

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69498/viewspace-925961/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/69498/viewspace-925961/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值