2021-04-28

#include<linux/init.h>
#include<linux/module.h>
#include<linux/fs.h>
#include<linux/kdev_t.h>
#include<linux/cdev.h>
#include<linux/device.h>

#define DEVICE_CLASS_NAME “chrdev_class_name”

#define DEVICE_NODE_NAME “chrdev_node_name”
static int major_num,minor_num;
module_param(major_num,int,S_IRUSR);
module_param(minor_num,int,S_IRUSR);
dev_t dev_num;

struct cdev cdev;
struct class class;
struct device device;
int chrdev_open(struct inode
nod,struct file
file)
{
printk(“hello chrdev_open\r\n”);
return 0;

}
struct file_operations chrdev_ops={
.owner = THIS_MODULE,
.open=chrdev_open

};

static int hello_init(void)
{
//printk(“hello\r\n”);

int ret;
if(major_num)
{
	dev_num=MKDEV(major_num,minor_num);

	ret=register_chrdev_region(dev_num,1,"wlw");
	if(ret<0)
	{
		printk("fail to register\r\n");
		return 0;
	}
	printk("ok to register\r\n");
}
else
{
	ret=alloc_chrdev_region(&dev_num,0,1,"wlw1");
	if(ret<0)
	{
		printk("fail to register\r\n");
		return 0;
	}
	printk("alloc to ok\r\n");

	major_num=MAJOR(dev_num);
	minor_num=MINOR(dev_num);
	printk("major=%d\n",major_num);
	printk("minor=%d\n",minor_num);
}
cdev.owner=THIS_MODULE;
cdev_init(&cdev,&chrdev_ops);
cdev_add(&cdev,dev_num,1);
class=class_create(THIS_MODULE,DEVICE_CLASS_NAME);
device=device_create(class,NULL,dev_num,NULL,DEVICE_NODE_NAME);

//printk("a=%d\r\n",a);
return 0;

}
static void hello_exit(void)
{

unregister_chrdev_region(MKDEV(major_num,minor_num),1);
cdev_del(&cdev);
device_destroy(class,dev_num);
class_destroy(class);

printk("exit\r\n");

}

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、付费专栏及课程。

余额充值