【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);
目录
相关文章
|
4月前
|
Linux 开发工具 Perl
在Linux中,有一个文件,如何删除包含“www“字样的字符?
在Linux中,如果你想删除一个文件中包含特定字样(如“www”)的所有字符或行,你可以使用多种文本处理工具来实现。以下是一些常见的方法:
65 5
|
5月前
|
Linux 开发工具 Perl
Linux命令替换目录下所有文件里有"\n"的字符为""如何操作?
【10月更文挑战第20天】Linux命令替换目录下所有文件里有"\n"的字符为""如何操作?
77 4
|
6月前
|
Linux 程序员 编译器
Linux内核驱动程序接口 【ChatGPT】
Linux内核驱动程序接口 【ChatGPT】
|
7月前
|
Java Linux API
Linux设备驱动开发详解2
Linux设备驱动开发详解
75 6
|
7月前
|
存储 缓存 Unix
Linux 设备驱动程序(三)(上)
Linux 设备驱动程序(三)
74 3
|
7月前
|
Linux
Linux 设备驱动程序(四)
Linux 设备驱动程序(四)
57 1
|
7月前
|
存储 数据采集 缓存
Linux 设备驱动程序(三)(中)
Linux 设备驱动程序(三)
77 1
|
7月前
|
存储 前端开发 大数据
Linux 设备驱动程序(二)(中)
Linux 设备驱动程序(二)
55 1
|
7月前
|
缓存 安全 Linux
Linux 设备驱动程序(二)(上)
Linux 设备驱动程序(二)
85 1
|
6月前
|
域名解析 负载均衡 网络协议
Linux网络接口配置不当所带来的影响
总而言之,Linux网络接口的恰当配置是保证网络稳定性、性能和安全性的基础。通过遵循最佳实践和定期维护,可以最大程度地减少配置错误带来的负面影响。
230 0