【Linux设备驱动】--0x02字符设备模块-使用alloc_chrdev_region接口

简介: 源代码 #include #include #include #include

源代码

alloc_chrdev_regionregister_chrdev_region的区别在于,
前者不知道主设备号,由操作系统自动分配
后者由人工设置主设备号!!

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>

#include <linux/slab.h>   // kfree,kmalloc
#include <linux/cdev.h>   // cdev_xxx
#include <linux/device.h> // device_xxx

static dev_t g_simple_cdev_dev_no;
static struct cdev *g_simple_cdev;
static struct class *g_simple_cdev_class;
static struct device *g_simple_cdev_device;

static int simple_cdev_open(struct inode *inode, struct file *file)
{
    return 0;
}

static int simple_cdev_release(struct inode *inode, struct file *file)
{
    return 0;
}

/* File operations struct for character device */
static const struct file_operations g_simple_cdev_fops = {
    .owner   = THIS_MODULE,
    .open    = simple_cdev_open,
    .release = simple_cdev_release,
};

static int __init simple_cdev_init(void)
{
    int ret;

    ret = alloc_chrdev_region(&g_simple_cdev_dev_no, 0, 1, "simple_cdev");
    if (ret < 0) {
        return ret;
    }

    g_simple_cdev = cdev_alloc();
    if (g_simple_cdev == NULL) {
        return -1;
    }
    g_simple_cdev->owner = THIS_MODULE;
    g_simple_cdev->ops   = &g_simple_cdev_fops;

    ret = cdev_add(g_simple_cdev, g_simple_cdev_dev_no, 1);
    if (ret < 0) {
        return ret;
    }

    g_simple_cdev_class  = class_create(THIS_MODULE, "simple_cdev");
    g_simple_cdev_device = device_create(g_simple_cdev_class, NULL, g_simple_cdev_dev_no, NULL, "simple_cdev");

    return 0;
}

static void __exit simple_cdev_exit(void)
{
    device_destroy(g_simple_cdev_class, g_simple_cdev_dev_no);
    class_destroy(g_simple_cdev_class);
    cdev_del(g_simple_cdev);
    unregister_chrdev_region(g_simple_cdev_dev_no, 1);
}

MODULE_LICENSE("GPL");
module_init(simple_cdev_init);
module_exit(simple_cdev_exit);
目录
相关文章
|
10天前
|
Linux 程序员 编译器
Linux内核驱动程序接口 【ChatGPT】
Linux内核驱动程序接口 【ChatGPT】
|
16天前
|
Java Linux API
Linux设备驱动开发详解2
Linux设备驱动开发详解
22 6
|
16天前
|
消息中间件 算法 Unix
Linux设备驱动开发详解1
Linux设备驱动开发详解
22 5
|
14天前
|
NoSQL Linux Android开发
内核实验(三):编写简单Linux内核模块,使用Qemu加载ko做测试
本文介绍了如何在QEMU中挂载虚拟分区、创建和编译简单的Linux内核模块,并在QEMU虚拟机中加载和测试这些内核模块,包括创建虚拟分区、编写内核模块代码、编译、部署以及在QEMU中的加载和测试过程。
77 0
内核实验(三):编写简单Linux内核模块,使用Qemu加载ko做测试
|
16天前
|
Ubuntu NoSQL Linux
Linux内核和驱动
Linux内核和驱动
15 2
|
6天前
|
域名解析 负载均衡 网络协议
Linux网络接口配置不当所带来的影响
总而言之,Linux网络接口的恰当配置是保证网络稳定性、性能和安全性的基础。通过遵循最佳实践和定期维护,可以最大程度地减少配置错误带来的负面影响。
25 0
|
9天前
|
Linux API
Linux里的高精度时间计时器(HPET)驱动 【ChatGPT】
Linux里的高精度时间计时器(HPET)驱动 【ChatGPT】
|
9天前
|
Linux 测试技术 API
Linux PWM接口概述 【ChatGPT】
Linux PWM接口概述 【ChatGPT】
|
18天前
|
关系型数据库 Linux PostgreSQL
【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误
【Azure 应用服务】Azure Function App Linux环境下的Python Function,安装 psycopg2 模块错误