自动创建设备节点,不需要使用mknod去创建/dev下的设备节点
流程
-
编译和挂载
makeinsmod 005_udev_mdev.ko -
查看
ls /sys/class/005_udev_mdev #struct class *class_test 的 class_create(THIS_MODULE, name)中的name对应lsmod #命令 Module Size Used by 005_udev_mdev 16384 0cat /proc/devices # 命令 Character devices: 237 005_udev_mdevls /dev/005_udev_mdev #device_create(class_test, NULL, dev_no, NULL, name)中的name对应 -
卸载
会卸载**/proc/devices**,/dev,/sys/class下有的东西
rmmod 005_udev_mdev.ko
代码:005_udev_mdev.c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/kdev_t.h>
#include <linux/device.h>
#include <linux/uaccess.h>
dev_t dev_no; // 设备号
struct cdev cdev_test; // 字符设备结构体
struct class *class_test; // 类
struct device *device_test; // 设备
static int test_open(struct inode *inode,struct file *file)
{
printk("open\n");
return 0;
}
static ssize_t test_read(struct file *file,char __user *buf, size_t size,loff_t *off){
printk("read\n");
return 0;
}
static ssize_t test_write(struct file *file,const char __user *buf, size_t size,loff_t *off){
printk("write\n");
*off += size;
return size;
}
static int test_release(struct inode *inode,struct file *file)
{
printk("release\n");
return 0;
}
struct file_operations fops = {
.owner = THIS_MODULE,
.open = test_open,
.read = test_read,
.write = test_write,
.release = test_release,
};
//设备名称
static char* name = "005_udev_mdev";
MODULE_LICENSE("GPL");
MODULE_AUTHOR("wyl");
MODULE_DESCRIPTION("005_udev_mdev");
static int modulecdev_init(void)
{
int ret;
ret = alloc_chrdev_region(&dev_no, 0, 1, name);
if (ret<0) {
printk("alloc_chrdev_region failed\n");
return ret;
}
printk("major:%d, minor:%d\n", MAJOR(dev_no), MINOR(dev_no));
cdev_init(&cdev_test, &fops);
cdev_add(&cdev_test, dev_no, 1);
class_test = class_create(THIS_MODULE, name); //创建类
device_test = device_create(class_test, NULL, dev_no, NULL, name);
return 0;
}
static void modulecdev_exit(void)
{
// 1. 先销毁设备节点
device_destroy(class_test, dev_no);
// 2. 销毁类 (原代码缺失此步,必须添加)
class_destroy(class_test);
// 3. 删除字符设备
cdev_del(&cdev_test);
// 4. 最后注销设备号
unregister_chrdev_region(dev_no, 1);
printk("modulecdev exit\n");
}
module_init(modulecdev_init);
module_exit(modulecdev_exit);
代码:app.c
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("/dev/005_udev_mdev", O_RDWR);
if (fd < 0) {
printf("open error\n");
return -1;
}
printf("open success\n");
close(fd);
return 0;
}