This blog content will not be a lot, mainly to the driver for a bit of optimization, each time to cat/proc/devices to see what the main device number can be too troublesome, Linux is so hot, obviously we do not have to do this every time.
In fact, the Register_chrdev function can help us to find a usable main device number from the 1~255, and then return the main device number to us, of course, this time we will also give the Register_chrdev function to pass a number, but this time is not transmitted 100, Instead of passing 0 in, when we pass 0, the Register_chrdev function will go to find out which main device number can also be used, according to a certain algorithm to determine which main device number to assign, and the assigned main device number as the return value.
We need a global variable to record the return value so that we can unregister_chrdev the argument in the First_drv_exit function and tell it what the main device number of the drive module we want to unload.
Enclosed are our improved driver 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) {&NBSP;&NBSP;&NBSP;&NBSP;PRINTK (kern_info "it is in first_drv_open.\n"); return 0;} Static int first_drv_release (Struct inode *inode, struct file *file) { &NBSP;&NBSP;&NBSP;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) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PRINTK (Kern_err "register_chrdev failure!\n"); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;-1;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;PRINTK (KERN_INFO "register_chrdev success...\n"); return 0;} Static void __exit first_drv_exit (void) { major = Unregister_chrdev (major, "First_drv"); if (major < 0) &NBSP;&NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;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");
This article is from the "12253782" blog, please be sure to keep this source http://12263782.blog.51cto.com/12253782/1874617
1th Linux Drive ___ automatically assigns a master device number