zoukankan      html  css  js  c++  java
  • Android 怎样在linux kernel 中读写文件

    前言
             欢迎大家我分享和推荐好用的代码段~~
    声明
             欢迎转载,但请保留文章原始出处:
             CSDN:http://www.csdn.net
             雨季o莫忧离:http://blog.csdn.net/luckkof

    正文

     

    [Description]
    怎样在linux kernel 中读写文件
     
    [Keyword]
    linux kernel read write file 读写文件
     
    [Solution]
    通常我们仅仅会在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稳定性
  • 相关阅读:
    python(4):Python应用场景
    python(3):python的优缺点
    MySQL(17):用户登录实例
    MySQL(16):参数化、封装
    MySQL(15):与python交互的增删改查
    MySQL(14):与python交互的类型
    MySQL(13):索引
    c++ --程序编译
    c++ -- 顺序容器操作
    c++ --string操作
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3851898.html
Copyright © 2011-2022 走看看