This article is written by xhz1234 (Xu Hongzhi). For more information, see the source.
Http://blog.csdn.net/xhz1234/article/details/38750091
In the previous blog, a character device driver is created. To use the features provided by the driver, you must manually create a character device file node. Is there a way to automatically create the corresponding device file node when the insmod device driver module is used? The answer is yes. One of the methods is to use a special character device, a miscellaneous device.
Principle: In the misc_init function of a miscellaneous device, a misc class is created and a character device driver is registered. The main device number of this character device is 10, when the misc_register function is called to register a miscellaneous device, a device node is created. If the minor of the miscellaneous device is misc_dynamic_minor, the system allocates a device number. Therefore, a miscellaneous device is eventually a character drive with the master device number 10.
Let's take a look at the sample code:
Miscellaneous Device Driver: misc_dev.c
#include <linux/module.h>#include <linux/kernel.h>#include <linux/fs.h>#include <linux/miscdevice.h>#define DEVICE_NAME "my_misc_dev"static int misc_open(struct inode *nd, struct file *filp){int major = MAJOR(nd->i_rdev);int minor = MINOR(nd->i_rdev);printk("misc_open,major=%d,minor=%d\n",major,minor);return 0;}static ssize_t misc_read(struct file *f, char __user *u, size_t sz, loff_t *off){printk("In the misc_read() function!\n");return 0;}struct file_operations misc_ops = {.owner = THIS_MODULE,.open = misc_open,.read = misc_read,};struct miscdevice misc = {.minor = MISC_DYNAMIC_MINOR,.name = DEVICE_NAME,.fops = &misc_ops,};static int demo_init(void){int ret;ret = misc_register(&misc);printk(DEVICE_NAME "\t initialized %s!\n", (0==ret)?"successed":"failed");return ret;}static void demo_exit(void){misc_deregister(&misc);printk("Removing misc_dev...!\n");}module_init(demo_init);module_exit(demo_exit);MODULE_LICENSE("GPL");MODULE_AUTHOR("Huoxin");MODULE_DESCRIPTION("An misc device driver as an example");
User Program: usr_app.c
#include <stdio.h>#include <fcntl.h>#include <unistd.h>#define MISC_DEV_NAME "/dev/my_misc_dev"int main(void){int ret;char buf[32];int fd = open(MISC_DEV_NAME, O_RDONLY|O_NDELAY);if(fd < 0){printf("open file %s failed\n", MISC_DEV_NAME);return -1;}read(fd, buf, 32);close(fd);return 0;}
After misc_dev.c is compiled, the driver module corresponding to insmod finds that the device file node of my_misc_dev is automatically created under the/dev directory.
Run the bin program corresponding to the user State program. dmesg gets the following print:
Aug 22 08:00:27 xhz-Rev-1-0 kernel: [2286.814994] misc_open, Major = 10, minor = 55
Aug 22 08:00:27 xhz-Rev-1-0 kernel: [2286.815002] In the misc_read () function!
Program source code: http://huoxin.github.io/miscdevice