Proc内核通信方式示例
1、内核模块实现创建Proc下的目录和文件以及读写操作
#include <linux/kernel.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/utsname.h> #include <linux/fs.h> #include <asm/uaccess.h> #include <linux/seq_file.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("SIR ZHANG"); MODULE_DESCRIPTION("test hello word"); static struct proc_dir_entry* des; static struct proc_dir_entry* parent; static ssize_t procfile_read(struct file *file, char __user *buf, size_t count, loff_t *offset) { int len; static char my_buffer[20]; if(*offset > 0) return 0; len = sprintf(my_buffer,"hello word\n"); copy_to_user(buf,my_buffer,len); printk("read helloword\n"); return len; } int procfile_open(struct inode *inode,struct file *file) { printk("open proc helloword\n"); return 0; } static ssize_t procfile_write(struct file *file, const char __user *buf, size_t count, loff_t *offset) { printk("write helloword\n"); return 0; } static struct file_operations f_ops = { .owner = THIS_MODULE, .read = procfile_read, .open = procfile_open, .write = procfile_write, }; int init_module() { parent = proc_mkdir("hello",NULL); //des = create_proc_entry("word",0777,parent); des = proc_create("word",0777,parent,&f_ops); //des->proc_fops = &f_ops; //des->read = printk("module load success\n"); return 0; } void cleanup_module() { //remove_proc_entry("word",parent); proc_remove(des); proc_remove(parent); printk("unload success\n"); } //module_init(init_module); //module_exit(cleanup_module);
2、内核模块的编译Makefile
ifneq ($(KERNELRELEASE),) obj-m := helloword.o module-objs := helloword.o else KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean: rm -f *.o *~core .depend *.mod.c Module.marker *.order *.ko endif

浙公网安备 33010602011771号