【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);
目录
相关文章
|
19天前
|
Linux 程序员 编译器
Linux内核驱动程序接口 【ChatGPT】
Linux内核驱动程序接口 【ChatGPT】
|
25天前
|
Java Linux API
Linux设备驱动开发详解2
Linux设备驱动开发详解
23 6
|
25天前
|
消息中间件 算法 Unix
Linux设备驱动开发详解1
Linux设备驱动开发详解
23 5
|
25天前
|
Ubuntu NoSQL Linux
Linux内核和驱动
Linux内核和驱动
16 2
|
29天前
|
监控 Linux
在Linux中,如何查看网络接口的状态?
在Linux中,如何查看网络接口的状态?
|
15天前
|
域名解析 负载均衡 网络协议
Linux网络接口配置不当所带来的影响
总而言之,Linux网络接口的恰当配置是保证网络稳定性、性能和安全性的基础。通过遵循最佳实践和定期维护,可以最大程度地减少配置错误带来的负面影响。
46 0
|
18天前
|
Linux API
Linux里的高精度时间计时器(HPET)驱动 【ChatGPT】
Linux里的高精度时间计时器(HPET)驱动 【ChatGPT】
|
18天前
|
Linux 测试技术 API
Linux PWM接口概述 【ChatGPT】
Linux PWM接口概述 【ChatGPT】
|
18天前
|
机器学习/深度学习 安全 网络协议
Linux防火墙iptables命令管理入门
本文介绍了关于Linux防火墙iptables命令管理入门的教程,涵盖了iptables的基本概念、语法格式、常用参数、基础查询操作以及链和规则管理等内容。
178 73
|
11天前
|
Linux Shell
Linux 中 Tail 命令的 9 个实用示例
Linux 中 Tail 命令的 9 个实用示例
40 6
Linux 中 Tail 命令的 9 个实用示例