Linux 自定义proc文件 a
Linux 自定义proc文件 a
=============================
使用"create_proc_entry"创建proc文件 -- 简单,但是写操作有缓冲区溢出的危险
环境
=============================
开发板:iTOP4412 A9
系统: Android4.0
内核:Linux3.0
1. jproca.c --- proc源码文件
#include <linux/module.h> #include <linux/sched.h> //jiffies #include <linux/proc_fs.h> #include <linux/uaccess.h> //copy_to|from_user()
#include <linux/slab.h>
static char *str = NULL; static int jproca_read(char *page, char **start, off_t off, int count, int *eof, void *data) { int ret = 0; ret = sprintf(page, "current kernel time is %ld\n", jiffies); ret += sprintf(page+ret, "str is %s\n", str); return ret; } static int jproca_write(struct file *filp, const char __user *buf, unsigned long count, void *data) { //分配临时缓冲区 char *tmp = kzalloc((count+1), GFP_KERNEL); if(!tmp) return -ENOMEM; //将用户态write的字符串拷贝到内核空间 if(copy_from_user(tmp, buf, count)) { kfree(tmp); return -EFAULT; } //将str的旧空间释放,然后将tmp赋值给str kfree(str); str = tmp; return count; } static int __init jproca_init(void) { struct proc_dir_entry *file; //创建proc文件 file = create_proc_entry("jproca", 0666, NULL); if(!file) { printk("Cannot create /proc/jproca\n"); return -1; } //将创建好的文件和读写函数关联在一起 file->read_proc = jproca_read; file->write_proc = jproca_write; return 0; } static void __exit jproca_exit(void) { //删除proc文件 remove_proc_entry("jproca", NULL); // signed 1 kfree(str); } module_init(jproca_init); module_exit(jproca_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("JUN");
2. Makefile
obj-m+=jproca.o CC=arm-none-linux-gnueabi-gcc KERNELDIR=/home/jun/iTop4412_Kernel_3.0 PWD:=$(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules install: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install depmod -A clean: $(MAKE) -C $(KERNELDIR) M=$(PWD) clean
3. 测试
# echo hellow > /proc/jproca # cat /proc/jproca # current kernel time is 1092794 # str is hellow ps: 重新操作echo会覆盖上一次操作的内容
------------ the end !!!
浙公网安备 33010602011771号