linux 内核驱动加载过程中 向文件系统中的文件进行读写操作

时间:2023-03-09 09:51:55
linux 内核驱动加载过程中  向文件系统中的文件进行读写操作

utils.h 文件:

#ifndef __UTILS_H__
#define __UTILS_H__ void a2f(const char *s, ...); #endif

utils.c 文件:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
#include <linux/string.h> #include "utils.h" #define FILE_PATH "/hzh" static struct file *fp; static int open_it() {
if (fp) return ;
mm_segment_t oldfs;
int err = ; oldfs = get_fs();
set_fs(get_ds());
fp = filp_open(FILE_PATH, O_CREAT|O_RDWR|O_APPEND, ); // 以追加方式写入文件
set_fs(oldfs);
if (IS_ERR(fp)) {
err = PTR_ERR(fp);
return ;
} return ;
} static void close_it() {
if (!fp) return;
filp_close(fp, );
fp = ;
} static int read_it(unsigned long long offset, unsigned char *data, unsigned int size) {
if (!fp) return ;
mm_segment_t oldfs;
int ret; oldfs = get_fs();
set_fs(get_ds()); ret = vfs_read(fp, data, size, &offset); set_fs(oldfs);
return ret;
} static int write_it(unsigned long long offset, unsigned char *data, unsigned int size) {
if (!fp) return ;
mm_segment_t oldfs;
int ret; oldfs = get_fs();
set_fs(get_ds()); ret = vfs_write(fp, data, size, &offset); set_fs(oldfs);
return ret;
} static int sync_it() {
if (!fp) return ;
vfs_fsync(fp, );
return ;
} void a2f(const char *fmt, ...) {
if (open_it()) return; char print_buf[];
va_list args;
int printed;
//初始化args,使其指向可变参数的第一个参数,fmt是可变参数的前一个参数
va_start(args, fmt);
printed = vsprintf(print_buf, fmt, args);
va_end(args); write_it(, print_buf, printed);
sync_it(); // close_it();
}