LINUX 字符设备自动创建文件节点

本文介绍了一个简单的Linux字符设备驱动程序实现过程。该程序通过注册字符设备,并创建相应的类和设备节点,实现了设备的基本初始化和退出操作。此外,还展示了如何分配字符设备号以及设备的增删管理。

#include <linux/init.h>

#include <linux/module.h>

#include <linux/cdev.h>

#include <linux/fs.h>

#include <linux/device.h>

 

MODULE_LICENSE("GPL");

 

#define DEVICE_NAME "hello"

#define DEVICE_CLASS_NAME"helloclass"

struct cdev mycdev;

dev_t device_node;

static struct class *helloclass;

 

static __init int hello_init(void)

{

         intrest;

        

         rest=alloc_chrdev_region(&device_node,0,1, DEVICE_NAME);

         if(rest < 0){

                   printk("%salloc_chrdev_region failed.\n",__func__);

                   returnrest;

         }

        

         cdev_init(&mycdev,NULL);

         mycdev.owner= THIS_MODULE;

         cdev_add(&mycdev,device_node, 1);

 

         helloclass =class_create(THIS_MODULE, DEVICE_CLASS_NAME);

         if(IS_ERR(helloclass)){

                   printk("%sclass_create failed.\n",__func__);

         }

        

         device_create(helloclass,NULL,device_node,NULL,DEVICE_NAME);

        

         printk(KERN_ALERT"%s -- hello world,are you ok!\n",__func__);

         return0;

}

 

static void hello_exit(void)

{

         cdev_del(&mycdev);

         device_destroy(helloclass,device_node);

         class_destroy(helloclass);

                  

         unregister_chrdev_region(device_node,1);

         printk(KERN_ALERT"%s -- hello world,are you ok!\n",__func__);

}

 

module_init(hello_init);

module_exit(hello_exit);

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值