在driver裡面,我們有時需要留一些資訊在磁碟上讓userspace作溝通,因此需要從kernel上直接寫入檔案。
相關API程式碼如下:
void InitKernelEnv(void){
oldfs = get_fs();
set_fs(KERNEL_DS);
}
void DinitKernelEnv(){
set_fs(oldfs);
}
struct file *OpenFile(char *path,int flag,int mode){
struct file *fp;
fp=filp_open(path, flag, 0);
if (fp) return fp;
else return NULL;
}
int WriteFile(struct file *fp,char *buf,int readlen) {
if (fp->f_op && fp->f_op->read)
return fp->f_op->write(fp,buf,readlen, &fp->f_pos);
else
return -1;
}
int ReadFile(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;
}
int CloseFile(struct file *fp) {
filp_close(fp,NULL);
return 0;
}
而使用方法請參考下面這個範例:
void test(){
char read_buf[2048] = "";
char write_buf[2048] = "";
struct file *fp;
InitKernelEnv();
//read file
fp = OpenFile(WPS_STA_LIST_FILE, O_RDONLY | O_CREAT, 0);
if(fp != NULL){
ReadFile(fp, read_buf, sizeof(read_buf));
}
CloseFile(fp);
//write to file
fp = OpenFile(WPS_STA_LIST_FILE, O_CREAT | O_WRONLY, 0);
if (fp!= NULL) {
WriteFile(fp, write_buf, sizeof(write_buf));
}
CloseFile(fp);
DinitKernelEnv();
}
參考資料:
[1] 請問內核中讀寫配置文件的源碼在哪個目錄的哪個文件中
[2] Reading file in kernel-簡單但實用