手把手教你在 linux 中创建节点,使其可以进行 cat 和 echo 。
我们测试驱动加载是否正常工作,一般都会写应用程序去测试,这样驱动程序中需要实现 open、read 函数和 write 函数,然后写一个应用程序通过 open 打开节点,获取 fb 文件描述符,进而对文件进行读写操作。
这里我介绍另外一种方法,我们可以在驱动中实现 show_xxx 和 set_xxx 函数,使这个节点可以进行 cat 和 echo 操作,源码如下:
test.c
#include #include #include #include #include #include #include #include static char mybuf[100]=123;//cat命令时,将会调用该函数static ssize_t show_my_device(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, %sn, mybuf);} //echo命令时,将会调用该函数static ssize_t set_my_device(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { sprintf(mybuf, %s, buf); return len;}//定义一个名字为my_device_test的设备属性文件static device_attr(my_device_test, s_iwusr|s_irusr, show_my_device, set_my_device); struct file_operations mytest_ops={ .owner = this_module,}; static int major;static struct class *cls;static int mytest_init(void){ struct device *mydev; major=register_chrdev(0,mytest, &mytest_ops); cls=class_create(this_module, mytest_class); //创建mytest_device设备 mydev = device_create(cls, 0, mkdev(major,0),null,mytest_device); //在mytest_device设备目录下创建一个my_device_test属性文件 if(sysfs_create_file(&(mydev- >kobj), &dev_attr_my_device_test.attr)) { return -1; } return 0;} static void mytest_exit(void){ device_destroy(cls, mkdev(major,0)); class_destroy(cls); unregister_chrdev(major, mytest);} module_init(mytest_init);module_exit(mytest_exit);module_license(gpl);makefile
kerneldir := /home/book/linux/tool/kernel/linux-imx-rel_imx_4.1.15_2.1.0_ga_alientekcurrent_path := $(shell pwd)obj-m := test.obuild: kernel_moduleskernel_modules: $(make) -c $(kerneldir) m=$(current_path) modulesclean: $(make) -c $(kerneldir) m=$(current_path) clean在 linux 中新建文件夹,将 test.c 和 makefile 放在一个文件夹中,进行编译,编译之前记得准备好你的 linux 内核源码,因为编译需要引用头文件,所以我们在 makefile 中写明 linux 内核源码目录(源码必须是编译过的源码,编译 linux 大概需要半个多小时)。另外需要注意,你编译驱动所引用的内核和你板子中真正运行的 linux 内核要需要是同一个版本,否则挂载不上去。
编译过程:
然后把 test.ko 传输过去,不管是使用 scp 命令还是使用 ftp 协议都可以。
加载驱动后cat:
echo
RTX 3090的性能比RTX 3080快10%至15%
长沙20个项目签约 千亿第三代半导体
苹果3nm加持的A17处理器有何优势?
Evan Blass爆料iPhone 7 将9月12日当周发布
思达阿波罗Apollo WLBI:先进集成的全方位测试解决方案
如何在Linux中创建节点
奥比中光3D视觉相机Gemini 2入选中国信通院“铸基计划”
差分信号PCB布局的3大误区,不看后悔
iQOO 3 5G新特性公布 手机上也能获得机械键盘的手感体验
基础电源、中间电源和峰值电源的解析
为什么FPGA成为数据中心尖端技术
rfid防盗系统是怎样设计实现的
一加9首次曝光:搭载骁龙875代号Lemonade
CJ物流携手爱立信开启5G专网时代
人工智能发展的神奇变化
AMD未来会有更低端的锐龙5系列处理器
这就尴尬了,华为p10和iPhone7售价一样,华为销售能超过苹果吗?
苹果M1处理器相当于一台什么配置的台式机
中微电荣获第八届“创客中国”深圳市中小企业创新创业大赛二等奖
售价仅为14.99美元的500MIPS多核开发板XMOS startKIT上市