/* test.c
* use "insmod test.ko"
* can see "/dev/test"
* and "test" in "/proc/devices"
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/types.h> /* dev_t */
#include <linux/cdev.h> /* struct cdev */
#include <linux/device.h> /* device_create() */
#include <linux/fs.h> /* struct file_operations */
#define DEVICE_NAME "test"
static struct cdev test_dev;
static struct class *test_class;
static dev_t test_devno;
static int test_open(struct inode *inode, struct file *filp)
{
printk(KERN_ALERT "The process is \"%s\" (pid %i)\n",
current->comm, current->pid);
return 0;
}
static struct file_operations test_fops =
{
.owner = THIS_MODULE,
.open = test_open,
};
static int __init test_init(void)
{
int ret;
unsigned int first_minor = 0;
unsigned int count = 1;
/* get dev_t from kernel */
ret = alloc_chrdev_region(&test_devno,first_minor,count,DEVICE_NAME);
if(ret < 0) return ret;
/* init cdev and fops */
cdev_init(&test_dev,&test_fops);
test_dev.owner = THIS_MODULE;/* add the dev_t to cdev */
cdev_add(&test_dev, test_devno,count);
/* create a class named as DEVICE_NAME, show as /sys/class/DEVICE_NAME */
test_class = class_create(THIS_MODULE, DEVICE_NAME);
if(IS_ERR(test_class))
{
printk(KERN_ALERT "create test_class error.");
return -1;
}
/* create device by /sys/class/DEVICE_NAME and the dev_t, show as /dev/DEVICE_NAME */
device_create(test_class,NULL,test_devno,NULL,DEVICE_NAME);
printk(KERN_ALERT DEVICE_NAME " initialized\n");
return 0;
}
static void __exit test_exit(void)
{
unsigned int count = 1;
cdev_del(&test_dev);
unregister_chrdev_region(test_devno,count);
device_destroy(test_class,test_devno);
class_destroy(test_class);
printk(KERN_ALERT DEVICE_NAME " released\n");
}
module_init(test_init);
module_exit(test_exit);
MODULE_LICENSE("GPL");
#Makefile
OBJ=test
ifneq ($(KERNELRELEASE),)
obj-m := ${OBJ}.o
module-objs := ${OBJ}.o
else
KERNELDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
defualt:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
clean:
rm *.o *.ko *.mod.c