CONTENTS
创建和访问proc
这里备份下代码:
Makefile:
obj-m := helloproc.o KERNEL_DIR := /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) all: make -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules clean: rm *.o *.ko *.mod.c .PHONY:clean
helloproc.c:
#include <linux/kernel.h> #include <linux/module.h> #include <asm/uaccess.h> #include <linux/proc_fs.h> MODULE_LICENSE("Dual BSD/GPL"); #define STR_MAX_SIZE 255 #define ROOT_PROC_ENTRY "hello_proc_entry" #define CHILD_PROC_NAME "hello_proc_str" #define INIT_STR_VALUE "Hello World From Kernel\n" static char string_var[STR_MAX_SIZE]; static struct proc_dir_entry * myprocroot; int string_read_proc(char *page, char **start, off_t off,int count, int *eof, void *data) { count = sprintf(page, "%s", (char *)data); return count; } int string_write_proc(struct file *file, const char __user *buffer, unsigned long count, void *data) { if (count > STR_MAX_SIZE) { count = STR_MAX_SIZE - 1; } memset(string_var, STR_MAX_SIZE, 1); copy_from_user(data, buffer, count); return count; } static int __init hello_init(void) { struct proc_dir_entry * entry; printk(KERN_ALERT "Hello, world\n"); myprocroot = proc_mkdir(ROOT_PROC_ENTRY, NULL); if (NULL == myprocroot) { return -1; } entry = create_proc_entry(CHILD_PROC_NAME, 0777, myprocroot); if (entry) { sprintf(string_var, "%s", INIT_STR_VALUE); entry->data = &string_var; entry->read_proc = &string_read_proc; entry->write_proc = &string_write_proc; }else { remove_proc_entry(ROOT_PROC_ENTRY, NULL); return -2; } return 0; } static void __exit hello_exit(void) { printk(KERN_ALERT "Goodbye, world\n"); remove_proc_entry(CHILD_PROC_NAME, myprocroot); remove_proc_entry(ROOT_PROC_ENTRY, NULL); } module_init(hello_init); module_exit(hello_exit);
需要注意的是,如果内核的版本号大于3.10,代码可能无法编译通过,参考【 http://my.oschina.net/fgq611/blog/173588 】。
使用方式及日志:
root@ubuntu:/hellomodule/helloworld# cd - /proc/hello_proc_entry root@ubuntu:/proc/hello_proc_entry# cat hello_proc_str Hello World From Kernel root@ubuntu:/proc/hello_proc_entry# echo "THIS IS FROM CONSOLE" > hello_proc_str root@ubuntu:/proc/hello_proc_entry# cat hello_proc_str THIS IS FROM CONSOLE
发表评论