前言
歡迎大家我分享和推薦好用的代碼段~~
聲明
歡迎轉載,但請保留文章原始出處:
CSDN:
雨季o莫憂離:
正文
[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);
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穩定性