testproc.c
-----------------------------------------------------------
#include
#include
#include
#include
#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