上一节讲到的字符设备注册与销毁是通过cdev_init、cdev_add、cdev_del等函数分步执行的,本小节用一种更简单的方式,来注册字符设备
register_chrdev
- 如果major为0,该函数将动态的分配一个主设备号并且返回对应的值
- 如果major > 0,该函数尝试获取该制定的设备号,并且申请成功,返回0
__register_chrdev函数原型:
unregister_chrdev
实验
操作截图
查看设备
代码
/*
*hello.c
*Original Author: luoyunheng, 2025-02-25
*
* Linux驱动之字符设备注册-register_chrdev
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <linux/cdev.h>
MODULE_LICENSE("GPL");
unsigned int major = 237;
int hello_open(struct inode *node, struct file *file)
{
printk("hello_open()\n");
return 0;
}
int hello_release(struct inode *node, struct file *file)
{
printk("hello_release()\n");
return 0;
}
static struct file_operations fops = {
.open = hello_open,
.release = hello_release,
};
static int hello_init(void)
{
int ret;
printk("hello_init()\n");
ret = register_chrdev(major, "loh", &fops);
if (ret < 0) {
printk("Major number allocated: %d\n", major);
return ret;
}
return 0;
}
static void hello_exit(void)
{
printk("hello_exit()\n");
unregister_chrdev(major, "loh");
return;
}
module_init(hello_init);
module_exit(hello_exit);
makefile
ifneq ($(KERNELRELEASE),)
obj-m:=hello.o
else
KDIR :=/lib/modules/$(shell uname -r)/build
PWD :=$(shell pwd)
all:
make -C $(KDIR) M=$(PWD) modules
clean:
rm -f *.ko *.o *.mod.o *.symvers *.cmd *.mod.c *.order
endif
应用程序
代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd;
fd = open("/dev/loh", O_RDWR);
if(fd < 0) {
perror("");
return 0;
}
sleep(10);
close(fd);
return 0;
}
字符设备驱动编写步骤总结