八、linux以模块方式注册设备
生活随笔
收集整理的這篇文章主要介紹了
八、linux以模块方式注册设备
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
????????我們剛剛在《六、linux虛擬平臺設備注冊》中,介紹了如何注冊一個設備,但是呢,那種方式適合在程序定型之后那樣做。當我們前期調試時,如果每一次都要編譯內核,那很浪費時間,所以,今天我們來講以模塊方式注冊設備。
? ? ? ? 我們先回顧一下剛剛注冊設備時使用的結構體(vim include/linux/platform_device.h):
????????那么我們首先要創建一個platform_device類型的結構體變量,并把這個變量通過platform_device_register注冊到內核中。
#include <linux/init.h> #include <linux/module.h>/*驅動注冊的頭文件,包含驅動的結構體和注冊和卸載的函數*/ #include <linux/platform_device.h>#define DRIVER_NAME "hello_ctl"MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("TOPEET");static void leds_release(struct device *dev) {printk("leds_release"); }struct platform_device platform_device_led = {.name = "my_code_led",.id = -1,.dev = {.release = leds_release,} };static int hello_init(void) {platform_device_register(&platform_device_led);return 0; }static void hello_exit(void) {platform_device_unregister(&platform_device_led); }module_init(hello_init); module_exit(hello_exit);我們創建了一個name為"my_code_led"的驅動,接下來我們要創建一個名字跟他匹配的驅動:
#include <linux/init.h> #include <linux/module.h>/*驅動注冊的頭文件,包含驅動的結構體和注冊和卸載的函數*/ #include <linux/platform_device.h>#define DRIVER_NAME "my_code_led"MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("TOPEET");static int hello_probe(struct platform_device *pdv){printk(KERN_EMERG "\tinitialized\n");printk("pdv->name is %s\n",pdv->name);printk("pdv->id is %d\n",pdv->id);pdv->dev.release(&pdv->dev);return 0; }static int hello_remove(struct platform_device *pdv){return 0; }static void hello_shutdown(struct platform_device *pdv){; }static int hello_suspend(struct platform_device *pdv){return 0; }static int hello_resume(struct platform_device *pdv){return 0; }struct platform_driver hello_driver = {.probe = hello_probe,.remove = hello_remove,.shutdown = hello_shutdown,.suspend = hello_suspend,.resume = hello_resume,.driver = {.name = DRIVER_NAME,.owner = THIS_MODULE,} };static int hello_init(void) {int DriverState;printk(KERN_EMERG "HELLO WORLD enter!\n");DriverState = platform_driver_register(&hello_driver);printk(KERN_EMERG "\tDriverState is %d\n",DriverState);return 0; }static void hello_exit(void) {printk(KERN_EMERG "HELLO WORLD exit!\n");platform_driver_unregister(&hello_driver); }module_init(hello_init); module_exit(hello_exit);????????然后,分別編譯成兩個模塊。記得先加載設備模塊,然后再加載驅動模塊,不然驅動模塊加載時,沒有匹配到對應設備名稱,將無法執行hello_probe。
? ? ? ? 命名有點亂,學習就先不管了。
? ? ? ? 再留下一個思考:如果設備有對應的參數,我們應該怎么體現出來呢?
總結
以上是生活随笔為你收集整理的八、linux以模块方式注册设备的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 七、linux驱动注册
- 下一篇: 九、linux设备节点注册