当前位置:网站首页 >> 产品/行业资讯 >>

从零开始编写Linux字符设备驱动程序(2)(基于友好的arm tiny4412开发板)

在上一节中,我们解释了如何编写第一个Linux字符设备驱动程序。

在本节中,我们将修改代码。

如下:#include& lt; linux / init.h& gt; #include& lt; linux / module.h& gt; #include& lt; linux / sched.h& gt; #include& lt; linux / kernel.h& gt; #include& lt; linux / cdev。

h& gt; #include& lt; linux / kdev_t.h& gt; #include& lt; linux / fs.h& gt; dev_t dev_no; static int __init& nbsp; cdev_test_init(void){int ret; printk(“ CDEV的HELLO KERNEL! ”); // 1,创建一个设备号->第一个是主要设备号,第二个是次要设备号// dev_no& nbsp; = MKDEV(222,2); // 2,已注册的设备号// count指示要分配多少个设备号// ret = register_chrdev_region(dev_no,1,“ my_dev”); //申请设备号ret = alloc_chrdev_region(& dev_no,1,1,“ my_dev”); if(ret& lt; 0){goto register_error;} register_error:return 0;} static int __exit cdev_test_exit(void){//注销驱动程序->表示unregister_chrdev_region(dev_no,1)之后写1; return 0;} module_init(cdev_test_init); module_exit(cdev_test_exit); MODULE_LICENSE(“ GPL”);然后重新编译并将内核映像下载到开发板:cat / proc / devices检查我们是否可以看到与my_dev对应的主要设备号是248。

驱动程序是222。

为什么这里是248,而不是222?因为在这里,我们在#include& lt; linux / fs.h& gt;下调用此函数。

头文件:extern int alloc_chrdev_region(dev_t *,unsigned,unsigned,const char *);此功能的功能是内核为我们分配一个设备号,该设备号由内核自动分配,因此我们无需使用MKDEV宏进行手动分配。

这也可以称为字符设备的动态分配方法。

函数原型如下:int alloc_chrdev_region(dev_t * dev,unsigned baseminor,unsigned count,const char * name){struct char_device_struct * cd; //调用__regis ter_chrdev_region注册字符设备cd = __register_chrdev_region(0,baseminor,count,name); //如果注册失败,则返回PTR_ERR(cd)错误代码。

如果(IS_ERR(cd))返回PTR_ERR(cd); //此处相同的是调用MKDEV分配设备号* dev = MKDEV(cd-& gt; major,cd-> baseminor);返回0;}

欢迎您的咨询