linux驱动学习——字符设备号

linux驱动学习——字符设备号,第1张

linux驱动学习——字符设备

字符设备号本质就是一个32位的无符号整型值。高12位为主设备号;低20位为次设备号。

  • 查看设备号
cat /proc/devices
4.1、构造设备号

源码路径: include/linux/kdev_t.h

#define MINORBITS	20
#define MINORMASK	((1U << MINORBITS) - 1)

#define MAJOR(dev)	((unsigned int) ((dev) >> MINORBITS))
#define MINOR(dev)	((unsigned int) ((dev) & MINORMASK))
#define MKDEV(ma,mi)	(((ma) << MINORBITS) | (mi))
4.2、注册/注销设备号
int register_chrdev_region(dev_t from, unsigned count, const char *name)
void unregister_chrdev_region(dev_t from, unsigned count)
4.3、示例代码
#include
#include
#include
#include

MODULE_LICENSE("GPL");
MODULE_AUTHOR("NEONAN");

static int major = 230;
static int minor = 0;
static dev_t devno;

static int hello_init(void)
{
	int result;

	printk("hello_initn");

	devno = MKDEV(major, minor);
	result = register_chrdev_region(devno, 1, "dev_test");
	if(result < 0){
		printk("register_chrdev_region fauiln");
		return result;
	}

	return 0;
}

static void hello_exit(void)
{
	printk("hello_exitn");
	unregister_chrdev_region(devno,1);
	return; 
}

module_init(hello_init);
module_exit(hello_exit);

编译后,注册该驱动

root@work:/home/work/dirve/dev_t# insmod dev_t.ko 
root@work:/home/work/dirve/dev_t# cat /proc/devices 
Character devices:
  ...
  230 dev_test

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/4664553.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-06
下一篇2022-11-06

发表评论

登录后才能评论

评论列表(0条)

    保存