简单字符驱动模板

来源:互联网 发布:mac口红日本买便宜多少 编辑:程序博客网 时间:2024/06/14 14:23
#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 nameobj_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_CFLAGSifeq ($(DEBUG),y) DEBFLAGS = -O -g -DDEBUG # "-O" is needed to expand inlineselse DEBFLAGS = -O2endifEXTRA_CFLAGS += $(DEBFLAGS)# call from kernel build systemifneq ($(KERNELRELEASE),)obj-m := $(obj_name).oelse# make modulesifeq ($(ARM_CROSS_COMPILE), y)KDIR := modules:make -C $(KDIR) M=$(PWD) modules ARCH=arm CROSS_COMPILE=chmod 755 *elseKDIR := /lib/modules/$(shell uname -r)/buildmodules:make -C $(KDIR) M=$(PWD) moduleschmod 755 *endif# make loadload:@/sbin/insmod $(obj_name).ko# make unloadunload:@/sbin/rmmod $(obj_name)# make clean.PHONY:cleanclean:@-rm -rf *.ko *.o *.mod.o *.mod.c *.symvers modul* .*.mod.o.cmd .tmp_versions .Makefile.swp .*.ko.cmd .*.o.cmdendif


0 0
原创粉丝点击