杂项设备实现原理

杂项设备的原理就是注册一个主设备号,将各种杂类设备都归属于该主设备号之下。

杂项设备本质上就是字符设备。

static int __init misc_init(void)
{
 int err;

#ifdef CONFIG_PROC_FS

//在proc文件系统下创建一个"misc"目录。 misc_proc_fops是该文件系统下文件的操作函数集。
 proc_create("misc", 0, NULL, &misc_proc_fops);
#endif//创建一个杂项设备类名为"misc"
 misc_class = class_create(THIS_MODULE, "misc");
 err = PTR_ERR(misc_class);
 if (IS_ERR(misc_class))
  goto fail_remove;

 err = -EIO;

//注册一个主设备号为MISC_MAJOR(10)的字符设备,设备操作函数集为misc_fops。
 if (register_chrdev(MISC_MAJOR,"misc",&misc_fops))
  goto fail_printk;
 return 0;

fail_printk:
 printk("unable to get major %d for misc devices\n", MISC_MAJOR);
 class_destroy(misc_class);
fail_remove:
 remove_proc_entry("misc", NULL);
 return err;
}
subsys_initcall(misc_init);//作为子系统添加到内核

 

//注册字符设备的具体实现如下
int register_chrdev(unsigned int major, const char *name,
      const struct file_operations *fops)
{
 struct char_device_struct *cd;
 struct cdev *cdev;
 char *s;
 int err = -ENOMEM;

//注册一个主设备号(major)和在该主设备号下的256个次设备号。

 cd = __register_chrdev_region(major, 0, 256, name);
 if (IS_ERR(cd))
  return PTR_ERR(cd);
 //为字符设备结构体分配内存空间
 cdev = cdev_alloc();
 if (!cdev)
  goto out2;

 cdev->owner = fops->owner;
 cdev->ops = fops

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值