major = register_chrdev(0, "hello", &hello_fops); /* (major, 0), (major, 1), ..., (major, 255)都对应hello_fops */
改写:
#define MAJOR(devid)
((unsigned int) ((devid) >> 20))
#define MINOR(devid)
((unsigned int) ((devid) & MINORMASK))
static struct cdev hello_cdev;
static int major;
static struct class *cls;
dev_t devid;//存放主设备号和次设备号 主设备号为高12位,次设备号为低20位
MINOR(devid)//取出次设备号
MAJOR(devid)//取出主设备号
MKDEV(major, 0)//把主设备号和次设备号组合成一个dev_t类型的设备号
if (major) //如果定义了主设备号,就不用分配了
{
devid = MKDEV(major, 0);//HELLO_CNT次设备号的个数,依次往后加
register_chrdev_region(devid, HELLO_CNT, "hello"); /* (major,0~1) 对应 hello_fops, (major, 2~255)都不对应hello_fops */
}
//"hello"设备名字
else
{
//分配次设备号以0开始HELLO_CNT次设备号
alloc_chrdev_region(&devid, 0, HELLO_CNT, "hello"); /* (major,0~1) 对应 hello_fops, (major, 2~255)都不对应hello_fops */
major = MAJOR(devid); //可以分配多个次设备号给这个设备
}
cdev_init(&hello_cdev, &hello_fops);
cdev_add(&hello_cdev, devid, HELLO_CNT);
cls = class_create(THIS_MODULE, "hello");//创建类
/* 在类下面创建三个设备节点 */
device_create(cls, NULL, MKDEV(major, 0), NULL, "hello0"); /* /dev/hello0 */
device_create(cls, NULL, MKDEV(major, 1), NULL, "hello1"); /* /dev/hello1 */
device_create(cls, NULL, MKDEV(major, 2), NULL, "hello2"); /* /dev/hello2 */
device_destroy(cls, MKDEV(major, 0));
device_destroy(cls, MKDEV(major, 1));
device_destroy(cls, MKDEV(major, 2));
class_destroy(cls);
cdev_del(&hello_cdev);
unregister_chrdev_region(MKDEV(major, 0), HELLO_CNT);
int register_chrdev_region(dev_t from, unsigned count, const char *name)