Android 怎樣在linux kernel 中讀寫文件

前言
         歡迎你們我分享和推薦好用的代碼段~~
聲明
         歡迎轉載,但請保留文章原始出處:
         CSDN:http://www.csdn.net
         雨季o莫憂離:http://blog.csdn.net/luckkof
linux

正文安全

 

[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穩定性
相關文章
相關標籤/搜索