lkm下のfreads
fopen.cのfopen/freads/fcloseをEXPORT_SYMBOLして、他のLKMからファイルの文字列単位での読み込みを実装したサンプルです。
fopen.c
#include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/syscalls.h> struct file *fopen(char *file, int mode); int freads(char *buff, int size, struct file *fp); int fclose(struct file *fp); struct file *fopen(char *fname, int mode) { struct file *fp; fp = filp_open(fname, mode, 0); if(IS_ERR(fp)) { return 0; } return fp; } int fclose(struct file *fp) { return filp_close(fp, NULL); } int freads(char *buf, int size, struct file *fp) { int index = 0; char a; int err = 0; while (kernel_read(fp, fp->f_pos++, &a, 1)) { if (a == 0x0a || index >= size - 1) { buf[index] = 0; err = index; break; } else { buf[index++] = a; } } return err; } static int __init fopen_init( void ) { return 0; } static void __exit fopen_exit( void ) { } module_init(fopen_init); module_exit(fopen_exit); EXPORT_SYMBOL(fopen); EXPORT_SYMBOL(freads); EXPORT_SYMBOL(fclose); MODULE_LICENSE( "GPL2" );
fread.c
#include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> struct file *fopen(char *file, int mode); int freads(char *buff, int size, struct file *fp); int fclose(struct file *fp); static char* file = ""; module_param(file, charp, S_IRUGO); static int __init fread_init( void ) { char buff[100]; struct file *fp; fp = fopen(fname, 0); if (fp) { while (freads(buff, 100, fp)) { printk("%s\n", buff); } fclose(fp); } else { printk("open err\n"); } return -1; } module_init(fread_init); MODULE_LICENSE( "GPL2" );
結果
[root@localhost north]# cat a.txt a bb ccc dddd eeeee ffffff ggggggg
[root@localhost north]# insmod fopen.ko [root@localhost north]# [root@localhost north]# insmod fread.ko file=a.txt insmod: error inserting 'fread.ko': -1 Operation not permitted [root@localhost north]# dmesg : [ 1274.667410] a [ 1274.667416] bb [ 1274.667420] ccc [ 1274.667423] dddd [ 1274.667426] eeeee [ 1274.667430] ffffff [ 1274.667435] ggggggg
[root@localhost north]# rmmod fopen.ko [root@localhost north]# insmod fread.ko file=a.txt insmod: error inserting 'fread.ko': -1 Unknown symbol in module [root@localhost north]# [root@localhost north]# dmesg : [ 4243.067933] fread: Unknown symbol freads (err 0) [ 4243.068029] fread: Unknown symbol fopen (err 0) [ 4243.068126] fread: Unknown symbol fclose (err 0)