一、
1、头文件
include/linux/fs.h
2、API
静态申请设备号
int register_chrdev_region(dev_t, unsigned, const char *);
动态分配设备号
int alloc_chrdev_region(dev_t *, unsigned, unsigned, const char *);
3、注销设备号
void unregister_chrdev_region(dev_t, unsigned);
二、静态申请设备号实例
1、驱动源代码
#include #include #include #include static int hello_major = 248; // 主设备号
static int hello_minor = 0; // 次设备号
static int number_of_devices = 1; // 设备的数量
static __init char_driver_init(void)
{
int result;
dev_t dev = 0;
dev = MKDEV (hello_major, hello_minor); // 主设备号、次设备号合并为设备号
result = register_chrdev_region (dev, number_of_devices, "hello"); // 静态注册设备号: name 体现在"/proc/devices"中
if (result<0) {
printk (KERN_ERR "char_driver_init: can't get major number %d\n", hello_major);
return result;
}
printk(KERN_INFO "char_driver_init\n");
return 0;
}
static __exit char_driver_exit(void)
{
dev_t devno = MKDEV (hello_major, hello_minor);// 主设备号、次设备号合并为设备号
unregister_chrdev_region (devno, number_of_devices);// 注销设备号
printk(KERN_INFO "char_driver_exit\n");
}
module_init(char_driver_init);
module_exit(char_driver_exit);
MODULE_LICENSE("GPL");
MODULE_VERSION("v1.0");
MODULE_AUTHOR("xz@vichip.com.cn");
MODULE_DESCRIPTION("Char Driver Module");
MODULE_ALIAS("char driver module");
2、Makefile
ifeq ($(KERNELRELEASE),)
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KERNELDIR) M=$(PWD) clean
else
obj-m := char_reg.o
endif
3、验证
1)make
2)sudo insmod char_reg.ko
3)cat /proc/devices
xiezhi@sdtpad-desktop:~/xiezhi/linux_drivers/char_reg$ cat /proc/devices
Character devices:
1 mem
4 /dev/vc/0
4 tty
4 ttyS
5 /dev/tty
5 /dev/console
5 /dev/ptmx
5 ttyprintk
6 lp
7 vcs
10 misc
13 input
14 sound
21 sg
29 fb
99 ppdev
108 ppp
116 alsa
128 ptm
136 pts
180 usb
189 usb_device
216 rfcomm
226 drm
248 hello
250 mei
251 hidraw
252 usbmon
253 bsg
254 rtc4)sudo rmmod char_reg