首页 > 代码库 > Char device registration

Char device registration

  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.

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

  Example of setuping a cdev(scull):

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

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

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

 

Char device registration