现在的位置: 首页 > 综合 > 正文

Example : Linux kernal file read and write

2019年06月01日 ⁄ 综合 ⁄ 共 748字 ⁄ 字号 评论关闭
// For Example : using filp_open save a log file to linux file system(or vm file system)
/*  
    "O_APPEND" : auto add information to the file last pos.  
  
    "get_fs()" : Get the old file permissions of the system current.  
    "set_fs(get_ds())" : Set linux kernal mode permissions for file opration(read,write).  
    "set_fs(old_fs)" : To restore the old permissions.  
*/
#include <linux/types.h>
#include <linux/fs.h>
static int mtd_flash_rom_log(const char *fn, size_t len, const u_char *buff)
{
    struct file *fp;
	mm_segment_t old_fs;
    fp = filp_open(fn, O_CREAT | O_RDWR | O_APPEND, S_IRWXU);
    if(IS_ERR(fp)) {
		printk("Open %s file failed\n", fn);
		return -1;
	}
    if((!fp->f_op) || (!fp->f_op->write))
	{         
		printk("%s file is not valid\n", fn);
		return -2;
	} else {
	    old_fs = get_fs();
		set_fs(get_ds());
		fp->f_op->write(fp, buff, len, &fp->f_pos);
		set_fs(old_fs);
	}
	filp_close(fp, NULL);
	return 0;
}

 

抱歉!评论已关闭.