Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1695704
  • 博文数量: 584
  • 博客积分: 13857
  • 博客等级: 上将
  • 技术积分: 11883
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-16 09:34

分类: LINUX

2009-12-16 10:52:10

It seems like the interface for creating modules has changed a bit, and udev is the way to go. Here is a short, quick and dirty module that creates /dev/pi with anonymous major and minor using udev.

The module creates the device (not the file) with register_chrdev , which returns the value of the major number that was assigned. We then use class_create to create a udev class to contain the device, finally you call device_create to actually make the device file.

To remove the device, you call device_destroy to remove the device from the class, then class_destroy to delete the class and finally unregister_chrdev to remove the device from the kernel (the device not the file).

The relevant init and exit sections are:
static int pi_init(void)
{
        struct device *err_dev;
 
        msg = kmalloc(sizeof(char)*DIGITS, GFP_ATOMIC);
 
        // register pi as a device
        pi_Major = register_chrdev(0, DEVICE_NAME, &fops);
 
        if (pi_Major < 0) {
                printk ("Failed to register device %s with error %d\n", DEVICE_NAME, pi_Major);
                return pi_Major;
        }
 
        /* create /dev/pi
         * we use udev to make the file
         */
        pi_class = class_create(THIS_MODULE,DEVICE_NAME);
        err_dev = device_create(pi_class, NULL, MKDEV(pi_Major,0),NULL,DEVICE_NAME);
 
        return 0;
}
 
/* remove the module
*/
static void pi_exit(void)
{
        /* free our memory, then destroy the device
         * then unregister the class and destroy it (unregister before destroy....important
         */
        kfree(msg);
        device_destroy(pi_class,MKDEV(pi_Major,0));
        class_destroy(pi_class);
        unregister_chrdev(pi_Major, DEVICE_NAME);
}
Hope that helps someone out there.

阅读(1015) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~