linux驱动学习——字符设备的注册

5.1、cdev

//分配
struct cdev *my_cdev = cdev_alloc();
//初始化
// cdev:  待初始化的cdev结构
// fops:  设备对应的操作函数集
void cdev_init(struct cdev *cdev, const struct file_operations *fops);
//注册, 告诉内核
// dev: 添加到内核的字符设备结构
// num: 设备号
// count: 关联到设备的设备号数目,通常为1
int cdev_add(struct cdev *dev, dev_t num, unsigned count);
//去除字符设备
void cdev_del(struct cedv *);

5.2、示例代码

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

MODULE_LICENSE("GPL");
MODULE_AUTHOR("ZZX");

static int major = 230;
static int minor = 0;
static dev_t devno;
static struct cdev cdev;
static int hello_open(struct inode *inode, struct file *ifilep)
{
	printk("hello open\n");
	return 0;
}
static struct file_operations hello_ops =
{
	.open = hello_open,
};

static int hello_init(void)
{
	int result;
	int error;

	printk("hello_init\n");

	devno = MKDEV(major, minor);
	result = register_chrdev_region(devno, 1, "dev_test");
	if(result < 0){
		printk("register_chrdev_region fauil\n");
		return result;
	}
	cdev_init(&cdev, &hello_ops);
	error = cdev_add(&cdev, devno, 1);
	if(error < 0)
	{
		printk("cdev_add fail\n");
		unregister_chrdev_region(devno,1);
		return error;
	}


	return 0;
}

static void hello_exit(void)
{
	printk("hello_exit\n");
	cdev_del(&cdev);
	unregister_chrdev_region(devno,1);
	return; 
}

module_init(hello_init);
module_exit(hello_exit);
mknode /dev/test c 230 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值