linux kernel read write file 读写文件

来源:互联网 发布:质量效应2梅伦数据 编辑:程序博客网 时间:2024/06/05 17:36
通常我们只会在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稳定性
0 0
原创粉丝点击