Chinaunix首页 | 论坛 | 博客
  • 博客访问: 178981
  • 博文数量: 80
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 83
  • 用 户 组: 普通用户
  • 注册时间: 2016-03-23 13:37
文章分类

全部博文(80)

文章存档

2016年(80)

我的朋友

分类: LINUX

2016-03-29 17:56:43

通常我们只会在linux native/app 层 读写文件,但可能有一些非常特别的情况下,我们需要直接
在Kernel 中读写文件信息。
下面给出典型的Code:
static struct file *open_file(char *path,int flag,int mode)
{
        struct file *fp;
        fp=filp_open(path, flag, mode);
        if (!IS_ERR_OR_NULL(fp)) return fp;

        else return NULL;

}
static int read_file(struct file *fp,char *buf,int readlen)
{
     if (fp->f_op && fp->f_op->read)
           return fp->f_op->read(fp,buf,readlen, &fp->f_pos);
     else
           return -1;
}
static int write_file(struct file *fp,char *buf,int len)
{
    if (fp->f_op && fp->f_op->write)
          return fp->f_op->write(fp, buf, len, &fp->f_pos);
    else
          return -1;
}
static int close_file(struct file *fp)
{
    filp_close(fp,NULL);
    return 0;
}
注意的是您在使用read_file & write_file 之前需要
//read set kernel domain
set_fs(KERNEL_DS);
在read_file & write_file 完成之后,需要
//need set user domain again
set_fs(USER_DS);
一定要成对的出现,不然将直接导致Kernel Crash.
最后强调一点: 如果能在linux native/app 层读写文件,尽量不要在Kernel 中去做这样的工作。
因为这个可能带来安全性的问题,以及可能因为新增代码而影响Kernel稳定性
阅读(1815) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~