​不使用mknod​,在驱动代码里自动生成设备号:


1.在内核驱动中用class_create,device_create两个函数,内核启动后就会在sysfs文件系统中建立相应的设备信息,记得把sysfs文件系统挂载到/sys,为下一步做准备

2.去官网下载udev,编译生成udevd,udevstart......等9个工具,只要把udevd,udevstart拷到自己的文件系统,配置好udev,并在系统启动时运行(可以在rcS脚本中加入),这样内核启动后,udev就会根据/sys里信息在/dev下建立设备文件.[1]


module被加载时,udev 自动在/dev下创建my_device设备文件(前提是用了class_create和class_device_create[2])。 我们在刚开始写Linux设备驱动程序的时候,很多时候都是利用mknod命令手动创建设备节点,实际上Linux内核为我们提供了一组函数,可以用来在模块加载的时候自动在 /dev目录下创建相应设备节点,并在卸载模块时删除该节点,当然前提条件是用户空间移植了udev。



​测试:查看设备,对比文件系统中的设备和驱动代码的关系​



#define DEVICE_NAME     "ledd"  /* 加载模式后,执行”cat /proc/devices”命令看到的设备名称 */
#define LED_MAJOR 231 /* 主设备号 */

static int __init s3c24xx_leds_init(void)
{
...
register_chrdev(LED_MAJOR, DEVICE_NAME, &s3c24xx_leds_fops);
leds_class = class_create(THIS_MODULE, "ledc");

leds_class_devs[0] = class_device_create(leds_class, NULL, MKDEV(LED_MAJOR, 0), NULL, "leds");
for (minor = 1; minor < 4; minor++)
{
leds_class_devs[minor] = class_device_create(leds_class, NULL, MKDEV(LED_MAJOR, minor), NULL, "led%d", minor);
if (unlikely(IS_ERR(leds_class_devs[minor])))
return PTR_ERR(leds_class_devs[minor]);
}

...
}
# cat /proc/devices
Character devices:
1 mem
2 pty
3 ttyp
...
231 ledd
253 usb_endpoint
254 rtc

# ls /sys/class/| grep led
ledc

# ls -l /sys/class/ledc
drwxr-xr-x 2 0 0 0 Jan 1 00:18 led1
drwxr-xr-x 2 0 0 0 Jan 1 00:18 led2
drwxr-xr-x 2 0 0 0 Jan 1 00:18 led3
drwxr-xr-x 2 0 0 0 Jan 1 00:18 leds

# ls -l /dev | grep led
crw-rw---- 1 0 0 231, 1 Jan 1 00:18 led1
crw-rw---- 1 0 0 231, 2 Jan 1 00:18 led2
crw-rw---- 1 0 0 231, 3 Jan 1 00:18 led3
crw-rw---- 1 0 0 231, 0 Jan 1 00:18 leds