ifneq ($(KERNELRELEASE),)
obj-m := proc.o
else
KDIR := /lib/modules/2.6.29/build
all:
make -C $(KDIR) M=$(PWD) modules
clean:
rm -f *.ko *.o *.mod.o *.mod.c *.symvers modul*
endif
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>
static struct proc_dir_entry *mydir;
static struct proc_dir_entry *pfile;
static char msg[255];
static int myproc_read(char *page, char **start, off_t off, int count, int *eof, void *data)
{
int len = strlen(msg);
if (off >= len)
return 0;
if (count > len - off)
count = len - off;
memcpy(page + off, msg + off, count);
return off + count;
}
static int myproc_write(struct file *file, const char __user *buffer, unsigned long count, void *data)
{
unsigned long count2 = count;
if (count2 >= sizeof(msg))
count2 = sizeof(msg) - 1;
if (copy_from_user(msg, buffer, count2))
return -EFAULT;
msg[count2] = '\0';
return count;
}
static int myproc_init(void)
{
mydir = proc_mkdir("mydir", NULL);
if (!mydir) {
printk(KERN_ERR "Can't create /proc/mydir\n");
return -1;
}
pfile = create_proc_entry("pool", 0666, mydir);
if (!pfile) {
printk(KERN_ERR "Can't create /proc/mydir/pool\n");
remove_proc_entry("mydir", NULL);
return -1;
}
pfile->read_proc = myproc_read;
pfile->write_proc = myproc_write;
return 0;
}
static void myproc_exit(void)
{
remove_proc_entry("pool", mydir);
remove_proc_entry("mydir", NULL);
}
module_init(myproc_init);
module_exit(myproc_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Xie");
copy from user 指从用户态来读到内核态
[root@localhost ~]# echo "Hello from kernel" > /proc/mydir/pool
[root@localhost ~]# cat /proc/mydir/pool
Hello from kernel
运行进程 echo将文件写入pool
杀死进程 则pool文件不存在