前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >手把手创建Linux设备属性节点,触发cat, echo操作

手把手创建Linux设备属性节点,触发cat, echo操作

作者头像
Jasonangel
发布2021-08-26 14:59:42
3.3K0
发布2021-08-26 14:59:42
举报
文章被收录于专栏:嵌入式Linux系统开发

手把手教你在 Linux 中创建节点,使其可以进行 cat 和 echo 。

我们测试驱动加载是否正常工作,一般都会写应用程序去测试,这样驱动程序中需要实现 open、read 函数和 write 函数,然后写一个应用程序通过 open 打开节点,获取 fb 文件描述符,进而对文件进行读写操作。

这里我介绍另外一种方法,我们可以在驱动中实现 show_xxx 和 set_xxx 函数,使这个节点可以进行 cat 和 echo 操作,源码如下:

test.c

代码语言:javascript
复制
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/regulator/consumer.h>
#include <sound/soc.h>
#include <sound/jack.h>
 
 
static  char mybuf[100]="123";
//cat命令时,将会调用该函数
static ssize_t show_my_device(struct device *dev,
                              struct device_attribute *attr, char *buf)        
{
    return sprintf(buf, "%s\n", 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

代码语言:javascript
复制
KERNELDIR := /home/book/linux/tool/kernel/linux-imx-rel_imx_4.1.15_2.1.0_ga_alientek
CURRENT_PATH := $(shell pwd)

obj-m := test.o

build: kernel_modules

kernel_modules:
 $(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules

clean:
 $(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean

在 Linux 中新建文件夹,将 test.c 和 Makefile 放在一个文件夹中,进行编译,编译之前记得准备好你的 Linux 内核源码,因为编译需要引用头文件,所以我们在 Makefile 中写明 Linux 内核源码目录(源码必须是编译过的源码,编译 Linux 大概需要半个多小时)。另外需要注意,你编译驱动所引用的内核和你板子中真正运行的 Linux 内核要需要是同一个版本,否则挂载不上去。

编译过程:

然后把 test.ko 传输过去,不管是使用 scp 命令还是使用 ftp 协议都可以。

加载驱动后cat:

echo

·················· END ··················

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-08-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 嵌入式Linux系统开发 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档