一、module模块test.c
#include <linux/module.h> #include "savefile.h" #define DIRNAME "/home/snail" #define FILENAME "my_log_a_core.bin" static char buf[] = "你好1234213"; int __init hello_init(void) { savefile(DIRNAME,FILENAME,buf,strlen(buf)); return 1; } void __exit hello_exit(void) { printk("hello exit\n"); } module_init(hello_init); module_exit(hello_exit);
二、savefile.c 与 savefile.h
#include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/uaccess.h> #include "savefile.h" int savefile(char *dirName,char *fileHeader,char *address,unsigned long length) { struct file *filp; mm_segment_t fs; loff_t pos; char filename[512]={'\0'}; unsigned int i=0; while(*dirName) { filename[i]=*dirName; i++; dirName++; } filename[i]='/'; i++; while(*fileHeader) { filename[i]=*fileHeader; i++; fileHeader++; } filename[i]='\0'; filp = filp_open(filename, O_RDWR| O_APPEND| O_CREAT, 0644); if(IS_ERR(filp)) { printk("open error...\n"); return 0; } fs=get_fs(); set_fs(KERNEL_DS); pos = 0; vfs_write(filp, address, length, &pos); set_fs(fs); filp_close(filp, NULL); return 1; }
#ifndef __SAVEFILE_H #define __SAVEFILE_H int savefile(char *dirName,char *fileHeader,char *address,unsigned long length); #endif
#ifndef __SAVEFILE_H #define __SAVEFILE_H int savefile(char *dirName,char *fileHeader,char *address,unsigned long length); #endif
三、makefile
obj-m := mytest.o //生成模块名 mytest-objs := test.o savefile.o //依赖文件 KDIR := /lib/modules/`uname -r`/build PWD := $(shell pwd) all: make -C $(KDIR) M=$(PWD) modules clean: rm -rf *.o .cmd *.ko *.mod.c .tmp_versions