Linux 编写一个 字符设备驱动
2021/7/18 7:08:20
本文主要是介绍Linux 编写一个 字符设备驱动,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Linux-DEVICE_ATTR()介绍及使用示例
驱动中动态创建设备号、设备节点
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/rockchip/common.h> #include <linux/kdev_t.h> #include <linux/device.h> /** struct hello_test_data { struct device *classdev; int blue=456; } static struct hello_test_data *hello_data; **/ static struct class *hello_test_class; //定义设备类 static struct device *classdev; static char mybuf[100]="123"; //执行cat会调用到此函数 show对应的是read static ssize_t hello_test_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%s\n", mybuf); } //执行echo 1 > hello_test会执行到此函数 store 对应的是write static ssize_t hello_test_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { sprintf(mybuf, "%s", buf); return count; } // _name _mode(权限) (显示函数) (写入) static DEVICE_ATTR(hello_test, 0777, hello_test_show, hello_test_store); //设备属性文件 名 // probe初始化函数 //cdev 分配设备对象空间 static int hello_test_probe(struct platform_device *pdev) { printk("Gatsby probe hello_test\n"); // 创建对应的节点file //device_create_file(&pdev->dev, &dev_attr_hello_test); classdev=device_create(hello_test_class, &pdev->dev, MKDEV(0, 0), NULL,"hello_test_device",0); sysfs_create_file(&pdev->dev.kobj, &dev_attr_hello_test.attr); return 0; } static const struct of_device_id hello_of_match[] = { { .compatible = "rockchip,hello_test"}, { }, }; // platform_driver 的结构 static struct platform_driver hello_test_driver = { .probe = hello_test_probe, .driver = { .name = "hello_test_class", .owner = THIS_MODULE, .of_match_table = hello_of_match, //需要再dts中做匹配 } }; static int __init hello_init(void) { printk("Gatsby hello_init\n"); /** struct device *classdev; classdev = device_create(hello_test, 0, MKDEV(0,0),NULL,"mytest_device"); //创建mytest_device设备 **/ hello_test_class = class_create(THIS_MODULE, "hello_test_class");// 在/sys/class目录下生成 hello_test目录 platform_driver_register(&hello_test_driver); return 0; } static void __exit hello_exit(void) { printk("Gatsby hello_exit\n"); platform_driver_unregister(&hello_test_driver); } module_init(hello_init); module_exit(hello_exit); MODULE_AUTHOR("hello_test"); MODULE_DESCRIPTION("Gatsby"); MODULE_LICENSE("GPL");makefile
obj-$(CONFIG_HELLO_TEST) += hello_test.okconfig
config HELLO_TEST tristate "Hello world for Gatsby" help Hello for Gatsby上一级目录 makefile
obj-y += gatsby/kconfig
source "drivers/gatsby/Kconfig"
这篇关于Linux 编写一个 字符设备驱动的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30[译]漫画SELinux概念
- 2024-03-29linux 移动文件
- 2024-03-28linux .so file
- 2024-03-28Linux 磁盘管理
- 2024-03-28Linux学习笔记(十三)磁盘管理(一):磁盘分区
- 2024-03-26linux 创建 文件
- 2024-03-25使用SecureCRT对Linux vim进行颜色设置
- 2024-03-202019-2020-12 20199317 《Linux内核原理与分析》 第十二周作业
- 2024-03-20Linux运维的第二周总结
- 2024-03-13how to count number of directories in linux