testproc.c
-----------------------------------------------------------
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>
#define MESSAGE_LENGTH 80
static char Message[MESSAGE_LENGTH] = "Helloworld\n";
static int read_procmem( char *buf, char **start, off_t offset,
int count, int *eof, void *data)
{
*eof = 1; //說明已經讀完
strcpy(buf, Message);
return strlen(Message); //返回讀入的字符數
}
static int write_procmem( struct file *file, const char *buffer,
unsigned long count, void *data)
{
strcpy(Message, buffer);
return strlen(Message); //返回寫入的字符數
}
static int __init init( void )
{
struct proc_dir_entry *p;
mode_t mode = S_IFREG | S_IWUGO | S_IRUGO;
// 什麼人都能寫 | 什麼人都能讀
p = create_proc_entry("abcdef", //proc文件名
mode,
NULL); //父目錄, NULL就是/proc目錄
if ( !p ) {
return ( -EINVAL );
}
p->size = 2131; //對外顯示的文件大小
p->owner = THIS_MODULE;
p->read_proc = read_procmem;
p->write_proc = write_procmem;
return 0;
}
static void __exit cleanup( void )
{
remove_proc_entry("abcdef", NULL);
}
module_init( init );
module_exit( cleanup );
MODULE_LICENSE("GPL");
-----------------------------------------------------
Makefile
-----------------------------------------------------
KERNELDIR=/usr/src/linux
include $(KERNELDIR)/.config
CFLAGS = -D__KERNEL__ -DMODULE -I$(KERNELDIR)/include -O -Wall
ifdef CONFIG_SMP
CFLAGS += -D__SMP__ -DSMP
endif
all:testproc.o
clean:
rm -f *.o *~ core
-------------------------------------------------------
然後切換到root用戶試試
#insmod testproc.o
#ls /proc/abcdef -l
-rw-rw-rw- 1 root root 2131 Apr 9 23:04 /proc/abcdef
#cat /proc/abcdef
Helloworld
#echo hahaha >/proc/abcdef
#cat /proc/abcdef
hahaha
#rmmod testproc