字符设备常用申请方法

大耗子 2020年02月24日 302次浏览

文章链接:https://codemouse.online/archives/1646846354

安装到设备上

insmod xxx.ko
rmmod xxx.ko
modinfo hello.ko 
lsmod 

申请

static int __init globalmem_init(void)
{
    int ret;
    dev_t devno = MKDEV(globalmem_major, 0);


    //分配cdev结构体,如果major是0,自动分配一个major
    if (globalmem_major)
        //手动分配
        ret = register_chrdev_region(devno, 1, "globalmem");
    else {
        //自动分配
        ret = alloc_chrdev_region(&devno, 0, 1, "globalmem");
        globalmem_major = MAJOR(devno);
    }
    
    if (ret < 0)
        return ret;
    
    globalmem_devp = kzalloc(sizeof(struct globalmem_dev), GFP_KERNEL);
    
    if (!globalmem_devp) {
        ret = -ENOMEM;
        goto fail_malloc;
    }
    
    globalmem_setup_cdev(globalmem_devp, 0);
    return 0;

fail_malloc:
    unregister_chrdev_region(devno, 1);
    return ret;
}
module_init(globalmem_init);

安装

static long globalmem_setup_cdev(struct globalmem_dev *dev, int index)
{
    int err, devno = MKDEV(globalmem_major, index);
    //对cdev结构体设置file_operations结构体
    cdev_init(&dev->cdev, &globalmem_fops);
    dev->cdev.owner = THIS_MODULE;
    //将cdev结构体注册入系统,系统能够识别调用当前cdev
    err = cdev_add(&dev->cdev, devno, 1);
    if (err)
    {
        printk(KERN_NOTICE "Error %d adding globalmem %d", err, index);
        return err;
    }
    
    //实现创建文件系统节点
    dev->lkm_memory_class = class_create(THIS_MODULE, "globalmem");
    if (IS_ERR(dev->lkm_memory_class))
        return PTR_ERR(dev->lkm_memory_class);
    device_create(dev->lkm_memory_class, NULL,MKDEV(globalmem_major,0),NULL,"globalmem");
}

退出

static void __exit globalmem_exit(void)
{
    cdev_del(&globalmem_devp->cdev);
    device_destroy(globalmem_devp->lkm_memory_class, MKDEV(globalmem_major, 0));
    class_destroy(globalmem_devp->lkm_memory_class);
    kfree(globalmem_devp);
    unregister_chrdev_region(MKDEV(globalmem_major, 0), 1);
}
module_exit(globalmem_exit);