Linux字符驱动之主设备号与次设备号

 // drv_demo.c

#include <linux/version.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/cdev.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <linux/delay.h>
#include <linux/time.h>
#include <linux/sched.h>
#include <linux/fs.h>

dev_t dev;
struct cdev  virdev;
static struct class *dev_class;

int openc(struct inode *inode,struct file *filep)
{
    printk ("in openc\n");
    return 0;
}

int releasec(struct inode *inode,struct file *filep)
{
    printk ("in releasec\n");
    return 0;
}

ssize_t writec (struct file *filep, const char __user *buf, size_t count,loff_t *offp)
{
    printk ("in writec\n");
    return 0;
}

ssize_t readc(struct file *filep, char __user *buf, size_t count, loff_t *offp)
{
    printk ("in readc\n");
    return 0;
}

int mymemmap(struct file* filep, struct vm_area_struct *vma)
{
    printk ("in mymemmap\n");
    return 0;
}

struct file_operations dev_fops={
    .owner =  THIS_MODULE,
    .open  =  openc,
    .read  =  readc,
    .write =  writec,
    .mmap  =  mymemmap,
    .release = releasec
};

static int __init dev_init(void)
{
    int status;
    int num = 0;
    struct device *rdev = NULL;

    status = alloc_chrdev_region(&dev, 0, 4, "dev_test");
    if( status ) {
            printk ("alloc chrdev region failed\n");
            return status;
    }

    cdev_init(&virdev, &dev_fops);
    virdev.owner = THIS_MODULE;
    cdev_add(&virdev, dev, 4);

    dev_class = class_create(THIS_MODULE, "dev_test");
    if (IS_ERR(dev_class)) {
        unregister_chrdev_region (dev, 4);
        return PTR_ERR(dev_class);
    }

    for (num = 0; num < 4; ++num) {
        rdev = device_create (dev_class, NULL, MKDEV (MAJOR(dev), num), NULL, "dev_test%d", num);
        status = PTR_RET(rdev);
        if (!!status) {
            printk  ("Error: device_create %d \n", num);
        }
    }

    printk ("in init\n");
    return 0;
}

static void __exit dev_exit(void)
{
    int num = 0;

    printk ("in exit\n");

    for (num = 0; num < 4; ++num) {
        device_destroy (dev_class, MKDEV (MAJOR(dev), num));
    }

    class_destroy (dev_class);

    cdev_del (&virdev);

    unregister_chrdev_region (dev, 4);

    printk ("end exit\n");
    return ;
}

module_init(dev_init);
module_exit(dev_exit);
MODULE_LICENSE("Dual BSD/GPL");

// Makefile

ifneq ($(KERNELRELEASE),)
	obj-m := drv_demo.o
else
	KERNELDIR ?= /lib/modules/$(shell uname -r)/build
	PWD := $(shell pwd)
default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD)  modules
endif
clean:  
	rm -rf *.mod.* *.o *.ko *.cmd *.symvers *.order 

如果觉得写得不错,烦请微信搜索公众号 "郑州行疆户外" 了解程序员的户外业余喜好。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值