linux驱动中保存文件的方法

       在linux驱动开发过程中,printk打印可能无法满足我们对实时性的要求,最简单的做法就是将值先存到变量里,待程序执行完成后保存到文件,将文件导出进行分析。

      但是在驱动代码里,一般是不会使用标准IO的(fopen、fwrite等),因为这些是应用层的东西。

在linux驱动中保存文件方法如下(特别要注意参数、不对的话系统会崩的。。):

#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/init.h>

static int save_data_to_file(const char* save_file_name, char *buff, int size)	//保存数据至文件
{
	struct file *fp = NULL;
	mm_segment_t fs;
	loff_t pos;
	printk("save_file_name = %s!\n",save_file_name);
	fp = filp_open(save_file_name, O_RDWR | O_CREAT, 0644);
	if (IS_ERR(fp))
	 {
	     printk("create file error/n");
	     return -1;
	 }
	 
	fs =get_fs();
	set_fs(KERNEL_DS);
	pos =0;
	vfs_write(fp, buff, size, &pos);

	filp_close(fp,NULL);
	set_fs(fs);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/fangye945a/article/details/108503118