2014年4月8日 星期二

[Linux]Read/Write config file in the driver module

#include linux/string.h

static int WriteBondConfToNCSI(void){
struct file *fp;
char buf[128],  *substring;
int indexofsubstring = 0;
mm_segment_t fs;

fp=filp_open("/conf/bond.conf",O_RDONLY,0);

fs = get_fs();
// Set segment descriptor associated to kernel space
set_fs(get_ds());

memset(buf, 0, sizeof(buf));

// Read the file
fp->f_op->read(fp, buf, 128, &fp->f_pos);
set_fs(fs);
filp_close(fp,NULL);

fp=filp_open("/conf/bond.conf",O_WRONLY | O_TRUNC,0);

substring = strstr(buf, "eth");
indexofsubstring = substring - buf;
buf[indexofsubstring+3] = '0';

fs = get_fs();
// Set segment descriptor associated to kernel space
set_fs(get_ds());

fp->f_op->write(fp, (char *)buf, strlen(buf), &fp->f_pos);

set_fs(fs);
filp_close(fp,NULL);

return 0;
}

如果想判斷某檔案是否存在,可利用下列方式:
filep=filp_open("/tmp/aa",O_RDONLY,0);
if(IS_ERR(filep)){
//Not exist
}
else{
//Exist
}

不可使用if(filep == NULL){}

沒有留言: