Char device registration

时间:2022-06-05 17:19:08

  The kernel uses structures of type struct cdev to represent char devices internally. Include <linux/cdev.h> so that you can use the following structures functions.

 struct cdev *cdev_alloc(void);                        //allocate a cdev
 void cdev_init(struct cdev *cdev, struct file_operations *fops);    //initialize it
 int cdev_add(sturct cdev *cdev, dev_t num, unsigned int count);     //add it to kernel
 void cdev_del(struct cdev *dev);                       //remove it

  Example of setuping a cdev(scull):

 static void scull_setup_cdev(struct scull_dev *dev, int index)
 {
     int err, devno = MKDEV(scull_major, scull_minor + index);
     cdev_init(&dev->cdev, &scull_fops);
     dev->cdev.owner = THIS_MODULE;
     dev->cdev.ops = &scull_fops;
     err = cdev_add (&dev->cdev, devno, );
     /* Fail gracefully if need be */
     if (err)
         printk(KERN_NOTICE "Error %d adding scull%d", err, index);
 }

  The older way to register and unregister a cdev is with:

 int register_chrdev(unsigned int major, const char *name, struct file_operations *fops);
 int unregister_chrdev(unsigned int major, const char *name);