KDD: dev number

设备驱动有个number,分为major和minor。

驱动安装后,在dev下面创建node,即驱动对应的文件,读写文件即使用驱动。

// hello.c
/**
# to make and install module
make
sudo insmod hello.ko

# print the installed module major number.
cat /proc/devices |grep winlin

# create node/file/device for driver
major=$(cat /proc/devices |grep winlin|awk '{print $1}')
sudo mknod /dev/winlin0 c ${major} 0
sudo mknod /dev/winlin1 c ${major} 1
sudo mknod /dev/winlin2 c ${major} 2
ll /dev/winlin*
#### crw-r--r-- 1 root root 249, 0 Jun  9 08:26 /dev/winlin0
#### crw-r--r-- 1 root root 249, 1 Jun  9 08:27 /dev/winlin1
#### crw-r--r-- 1 root root 249, 2 Jun  9 08:27 /dev/winlin2

# remove node/file/device
sudo rm -f /dev/winlin*

# remove module
sudo rmmod hello.ko
*/
#include 
#include 
#include 
MODULE_LICENSE("Dual BSD/GPL");

// the major number, alloc if 0.
static int winlin_major = 0;
// the minor number.
static int winlin_minor = 0;

static dev_t dev;

static int hello_init(void){
    printk(KERN_ALERT "hello, world, init. d=%d.\n", 3);
    
    if(winlin_major){
        dev = MKDEV(winlin_major, winlin_minor);
        printk(KERN_ALERT "MKDEV for device success, major=%d, minor=%d\n", MAJOR(dev), MINOR(dev));
    }
    else{
        // int alloc_chrdev_region(dev_t *dev, unsigned int firstminor, unsigned int count, char *name);
        if(alloc_chrdev_region(&dev, winlin_minor, 1, "winlin") == -1){
            printk(KERN_ALERT "alloc_chrdev_region for device failed\n");
            return -1;
        }
        winlin_major = MAJOR(dev);
        printk(KERN_ALERT "alloc_chrdev_region for device success, major=%d, minor=%d\n", MAJOR(dev), MINOR(dev));
    }
    
    // int register_chrdev_region(dev_t first, unsigned int count, char *name);
    if(register_chrdev_region(dev, 1, "winlin") == -1){
        printk(KERN_ALERT "register_chrdev_region for device failed\n");
        return -1;
    }
    printk(KERN_ALERT "register_chrdev_region for device success\n");
    
    return 0;
}

static void hello_exit(void){
    printk(KERN_ALERT "cleanup when exit, major=%d, minor=%d\n", MAJOR(dev), MINOR(dev));
    
    // void unregister_chrdev_region(dev_t first, unsigned int count);
    unregister_chrdev_region(dev, 1);
    printk(KERN_ALERT "unregister_chrdev_region for device\n");
    
    printk(KERN_ALERT "goodbye, exit\n");
}

module_init(hello_init);
module_exit(hello_exit);

编译的Makefile,在centos6下面测试通过:

# Makefile
obj-m = hello.o
KVERSION = $(shell uname -r)
all:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean


你可能感兴趣的:(KDD: dev number)