本篇博客内容不会很多,主要是对这个驱动程序进行一点优化,每次都要cat /proc/devices去查看还有哪些主设备号可用太麻烦了,linux如此受到热捧,显然我们不是每次都得这样做。
其实register_chrdev函数可以帮我们从1~255里面找到一个可用的主设备号,然后将这个主设备号返回给我们,当然这次我们同样要给register_chrdev函数传一个数字进去,只不过这次不是传100了,而是传0进去,当我们传0的时候,register_chrdev函数就会去查找还有哪个主设备号还可以用,根据一定的算法最终确定要分配哪个主设备号,并且把分配出来的主设备号当成返回值返回。
我们需要用一个全局变量来记录这个返回值,以便于在first_drv_exit函数中unregister_chrdev传参,告诉它我们要卸载的驱动模块的主设备号是多少。
下面附上我们改进后的驱动程序first_drv.c:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
int major = 0;
static int first_drv_open(struct inode *inode, struct file *file)
{
printk(KERN_INFO"It is in first_drv_open.\n");
return 0;
}
static int first_drv_release(struct inode *inode, struct file *file)
{
printk(KERN_INFO"It is in first_drv_release.\n");
return 0;
}
static const struct file_operations first_drv_fops = {
.owner = THIS_MODULE,
.open = first_drv_open,
.release = first_drv_release,
};
static int __init first_drv_init(void)
{
major = register_chrdev(0, "first_drv", &first_drv_fops);
if(major < 0)
{
printk(KERN_ERR"Register_chrdev failure!\n");
return -1;
}
printk(KERN_INFO"Register_chrdev success...\n");
return 0;
}
static void __exit first_drv_exit(void)
{
int ret = -1;
ret = unregister_chrdev(major, "first_drv");
if(ret < 0)
{
printk(KERN_INFO"Unregister_chrdev failure!\n");
}
printk(KERN_INFO"Unregister_chrdev success...\n");
}
module_init(first_drv_init);
module_exit(first_drv_exit);
MODULE_LICENSE("GPL");