procfs.c代码:
/*编写一个模块,当模块被加载时,该模块会向/proc文件系统中创建目录proc_test,然后在这个目录下创建一个只读文件current,一个可读可写文件hello,一个链接current_too */
#include MODULE_LICENSE("GPL"); #define BUFSIZE 1024static char global_buffer[BUFSIZE];static struct proc_dir_entry *example_dir,*hello_file,*current_file,*symlink; static int proc_read_current(char *page,char **start,off_t off,int count,int *eof,void *data){ //当用户读取current文件的内容时,内核调用这个函数 int len; len=sprintf(page,"current process-->name:%s gid:%d pid:%d\\n", current->comm,current->signal->pgrp,current->pid); return len;} static int proc_read_hello(char *page,char **start, off_t off,int count,int *eof,void *data){ //当用户读取hello文件的内容时,内核调用这个函数 int len; len=sprintf(page,"%s",global_buffer); return len;} static int proc_write_hello(struct file *file,const char *buffer,unsigned long count,void *data){ //当用户写hello文件的内容时,内核调用这个函数 int len; if(count>BUFSIZE-1) len=BUFSIZE-1; //如果写内容过长,则截断 else len=count; //从用户的缓冲区获得要写的数据 if(copy_from_user(global_buffer,buffer,len)) return -EFAULT; global_buffer[len]='\\0'; return len;} static int proc_init(void){ example_dir=proc_mkdir("proc_test",NULL); //创建目录 /proc/proc_test example_dir->owner=THIS_MODULE; //创建只读文件 /proc/proc_test/current current_file=create_proc_read_entry("current",0444,example_dir,proc_read_current,NULL); current_file->owner=THIS_MODULE; //创建一个可读可写的文件 /proc/proc_test/hello hello_file=create_proc_entry("hello",04,example_dir); strcpy(global_buffer,"hello"); //预设文件内容为hello hello_file->read_proc=proc_read_hello; hello_file->write_proc=proc_write_hello; hello_file->owner=THIS_MODULE; //创建一个链接 /proc/proc_test/current_too,指向current symlink=proc_symlink("current_too",example_dir,"current"); symlink->owner=THIS_MODULE; return 0;} static void proc_exit(void){ remove_proc_entry("current_too",example_dir); remove_proc_entry("helloo",example_dir); remove_proc_entry("current",example_dir); remove_proc_entry("proc_test",NULL);}module_init(proc_init);module_exit(proc_exit); procfs.c目录下的Makefile文件代码: ifneq ($(KERNELRELEASE),) obj-m := procfs.o else KDIR?=/lib/modules/$(shell uname -r)/build PWD:=$(shell pwd) default: $(MAKE) -C $(KDIR) M=$(PWD) modules clean: $(MAKE) -C $(KDIR) M=$(PWD) clean endif 命令: #make 查看原来的proc #insmod procfs.ko #cd /proc #ls #cd proc_test #ls #lsmod procfs #cat current current只读 #cat hello hello是可读可写 #echo “12345”>hello #cat hello #cat current_too current_too是链接 #rmmod procfs 下载本文