1.问题出现

  我在尝试最简单的字符设备驱动的程序。编译好之后加载模块显示这个错误,同时还有这个错误

# dmesg | tail -10
[ 1676.443388] hello_init
[ 1676.443404] register_chrdev_region fail 
[ 1712.696222] hello_init
[ 1712.696240] he register_chrdev_region fail 
[ 1712.703983] hello_init
[ 1712.703997] he register_chrdev_region fail 
[ 4005.040674] hello_init
[ 4005.043149] my register_chrdev_region fail 
[ 4005.049060] hello_init
[ 4005.051530] my register_chrdev_region fail 

我的代码:hello.c

#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>

static int major=250;//主设备号(用于区分设备类)
static int minor=0;//次设备号(用于区分哪个设备)

static dev_t devno;
static struct cdev cdev1;
static int hello_open(struct inode *inodep,struct file *filep)
{
    printk(KERN_ALERT "hello_open\r\n!");
    return 0;
}

static struct file_operations hello_ops={ 
    .open=hello_open,
};

static int hello_init(void)
{
    int ret;
    printk(KERN_ALERT "hello_init\r\n");
    devno=MKDEV(major,minor);//第一步:将主设备号、次设备号转化成dev_t类型
    ret=register_chrdev_region(devno,1,"hello");
    if(ret < 0)
    {
        printk(KERN_ERR "my register_chrdev_region fail \r\n");
        return ret;
    }
    printk(KERN_INFO "register_chrdev_region success\n");
    //第二步:注册字符设备驱动
    cdev_init(&cdev1,&hello_ops);
    ret=cdev_add(&cdev1,devno,1);
    if(ret<0)
    {
        printk(KERN_ERR "Uable to add dev\n");
        return ret;
    }
    return 0;
}
static void hello_exit(void)
{
    cdev_del(&cdev1);
    unregister_chrdev_region(devno,1);
    printk(KERN_ALERT "hell_exit\r\n");
}
MODULE_LICENSE("GPL");
module_init(hello_init);
module_exit(hello_exit);

2.问题解决

因为我查看

# cat /proc/devices 
Character devices:
  1 mem
  2 pty
  3 ttyp
  4 /dev/vc/0
  4 tty
  4 ttyS
  5 /dev/tty
  5 /dev/console
  5 /dev/ptmx
  7 vcs
 10 misc
 13 input
 29 fb
 89 i2c
 90 mtd
116 alsa
128 ptm
136 pts
180 usb
189 usb_device
226 drm
248 ttyGS
249 bsg
250 watchdog
251 ptp
252 pps
253 rtc
254 gpiochip

Block devices:
  8 sd
 65 sd
 66 sd
 67 sd
 68 sd
 69 sd
 70 sd
 71 sd
128 sd
129 sd
130 sd
131 sd
132 sd
133 sd
134 sd
135 sd
179 mmc
259 blkext

发现250已经有了watchdog,所以必然会冲突。

所以我把

static int major=250;//主设备号(用于区分设备类)

修改成了

static int major=99;//主设备号(用于区分设备类)

就好了