Linux设备属性节点读写操作----cat 、echo

1. 具体实现代码如下:

// drv_attr.c
#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 __init 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 __exit 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");

2.实现的makefile如下:

KERNELDIR := /home/xdh/linux/IMX6ULL/linux/temp/linux-imx-rel_imx_4.1.15_2.1.0_ga_alientek

CURRENT_PATH := $(shell pwd)
obj-m := testbeep.o
build: kernel_modules
kernel_modules:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) modules
clean:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean

3.具体使用如下:

安装mytest_device驱动后,会生成一个叫my_device_test的节点。具体操作如下:
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路过的小熊~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值