Linux设备驱动之字符设备 【1】创建字符设备

  创建一个字符设备并在/dev目录下创建节点的基本步骤:


#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/stddef.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/cdev.h>
#include <linux/types.h>

#define Hello_Major     250
#define Hello_Minor     0
#define Count_of_Device 1

struct cdev cdev;
dev_t dev = 0;

struct file_operations hello_fops = {
    .owner = THIS_MODULE,
};

struct class *my_class;

static void char_reg_setup_cdev(void)
{
    int error, devno = MKDEV(Hello_Major,Hello_Minor);

    /**
     * 初始化cdev结构体
     **/ 
    cdev_init(&cdev, &hello_fops);
    cdev.owner = THIS_MODULE;
    cdev.ops = &hello_fops;

    /**
     * 将cdev结构体加入内核
     **/ 
    error = cdev_add(&cdev, devno, 1);
    if(error)
    {
        printk(KERN_NOTICE " Error %d adding char_reg_setup_cdev", error);
    }


    /*********************** 自动创建节点 **************************/
    /**
     * 创建设备类,用于device_create()的调用,
     * 并使该设备类在卸载驱动时,能调用class_destroy()删除
     **/
    my_class = class_create(THIS_MODULE, "farsight_class");
    if(IS_ERR(my_class))
    {
        printk("ERR: failed in creating class.\n");
        return;
    }

    /**
     * 在/dev目录下创建设备,命名为hello,并将之与创建的类关联
     **/ 
    device_create(my_class, NULL, devno, NULL, "hello");
}

static int __init hello_init(void)
{
    int result;

    /**
     * 通过主设备号和次设备号获取设备编号
     * 设备号用32bits表示,
     * 高20bits用于表示主设备号,用于标识设备对应的驱动程序;
     * 低12位表示次设备号,用于确定设备文件所指的设备
     **/
    dev = MKDEV(Hello_Major,Hello_Major);

    /**
     * 将驱动程序和设备编号关联,并将该关联信息保存到/proc/device文件中
     **/
    result = register_chrdev_region(dev, Count_of_Device,"test");
    if(result < 0)
    {
        printk("hello: can't get major number %d\n", Hello_Major);
        return result;
    }

    /**
     * 创建节点
     **/ 
    char_reg_setup_cdev();
    printk(KERN_INFO "char device registered\n");
    return 0;
}

static void __exit hello_exit(void)
{
    dev_t devno = MKDEV(Hello_Major, Hello_Minor);

    /* 释放cdev结构体 */
    cdev_del(&cdev);

    /* 释放设备编号 */
    unregister_chrdev_region(devno, Count_of_Device);

    /* 删除设备节点 */
    device_destroy(my_class, devno);

    /* 删除设备类 */
    class_destroy(my_class);
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值