linux设备模型(四 platform )

时间:2022-07-20 17:53:42

(1)提高程序可移植性

(2)


#include <linux/device.h>

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/platform_device.h>


MODULE_AUTHOR("David Xie");
MODULE_LICENSE("Dual BSD/GPL");


static struct platform_device *my_device;


static int __init my_device_init(void)
{
int ret = 0;
        
        /* 分配结构 */
my_device = platform_device_alloc("my_dev", -1);
        
        /*注册设备*/
ret = platform_device_add(my_device);

/*注册失败,释放相关内存*/
if (ret)
   platform_device_put(my_device);

return ret;
}


static void my_device_exit(void)
{
platform_device_unregister(my_device);
}


module_init(my_device_init);

module_exit(my_device_exit);


#include <linux/device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/platform_device.h>


MODULE_AUTHOR("David Xie");
MODULE_LICENSE("Dual BSD/GPL");


static int my_probe(struct device *dev)
{
    printk("Driver found device which my driver can handle!\n");
    return 0;
}


static int my_remove(struct device *dev)
{
    printk("Driver found device unpluged!\n");
    return 0;
}


static struct platform_driver my_driver = {
.probe = my_probe,
.remove = my_remove,
.driver = {
.owner = THIS_MODULE,
.name = "my_dev",
},
};


static int __init my_driver_init(void)
{       
        /*注册平台驱动*/
return platform_driver_register(&my_driver);
}


static void my_driver_exit(void)
{
platform_driver_unregister(&my_driver);
}


module_init(my_driver_init);
module_exit(my_driver_exit);