#include <linux/init.h> #include <linux/module.h> #include <linux/types.h> #include <linux/cdev.h> #include <linux/fs.h> #include <linux/device.h> dev_t devid; static struct cdev *xx_cdev; static int xx_major = 0; static int xx_minor = 0; static struct class *xx_class; static int xx_open(struct inode *inode, struct file *file) { printk("xx_open called!\n"); return 0; } static int xx_release(struct inode *inode, struct file *file) { printk("xx_release called!\n"); return 0; } static struct file_operations xx_ops = { .owner = THIS_MODULE, .open = xx_open, .release= xx_release, }; static int __init xx_init(void) { int err; /* init xx_cdev */ xx_cdev = cdev_alloc(); cdev_init(xx_cdev, &xx_ops); xx_cdev->owner = THIS_MODULE; /* get device id */ alloc_chrdev_region(&devid, 0, 1, "xx_cdev"); xx_major = MAJOR(devid); xx_minor = MINOR(devid); printk("xx_major = %d\n", xx_major); printk("xx_minor = %d\n", xx_minor); /* add xx_cdev */ err = cdev_add(xx_cdev, devid, 1); if (err) { printk("Error %d: adding xx_cdev failed!\n", err); return -1; } /* create xx_class * udev will create the device inode with xx_class */ xx_class = class_create(THIS_MODULE, "xx_class"); if (IS_ERR(xx_class)) { printk("Error %d: create xx_class failed!\n", xx_class); return -1; } device_create(xx_class, NULL, devid, NULL, "xx_cdev"); return 0; } static void __exit xx_exit(void) { unregister_chrdev_region(devid, 1); cdev_del(xx_cdev); device_destroy(xx_class, devid); class_destroy(xx_class); } module_init(xx_init); module_exit(xx_exit); MODULE_LICENSE("GPL");
内核版本:ubuntu 12.04(3.2.0-23-generic)
Makefile参考
# Makefile for kernel module # # Author: xxxx # Email: xxxx at gmail dot com # module name obj_name=cdev # Comment/uncomment the following line to disable/enable arm_cross_compile #ARM_CROSS_COMPILE = y # Comment/uncomment the following line to disable/enable debugging #DEBUG = y # Add your debugging flag (or not) to EXTRA_CFLAGS ifeq ($(DEBUG),y) DEBFLAGS = -O -g -DDEBUG # "-O" is needed to expand inlines else DEBFLAGS = -O2 endif EXTRA_CFLAGS += $(DEBFLAGS) # call from kernel build system ifneq ($(KERNELRELEASE),) obj-m := $(obj_name).o else # make modules ifeq ($(ARM_CROSS_COMPILE), y) KDIR := modules: make -C $(KDIR) M=$(PWD) modules ARCH=arm CROSS_COMPILE= chmod 755 * else KDIR := /lib/modules/$(shell uname -r)/build modules: make -C $(KDIR) M=$(PWD) modules chmod 755 * endif # make load load: @/sbin/insmod $(obj_name).ko # make unload unload: @/sbin/rmmod $(obj_name) # make clean .PHONY:clean clean: @-rm -rf *.ko *.o *.mod.o *.mod.c *.symvers modul* .*.mod.o.cmd .tmp_versions .Makefile.swp .*.ko.cmd .*.o.cmd endif