linux sys属性节点创建

#include <linux/module.h>
#include <linux/slab.h>
#include <linux/kobject.h>
#include <linux/platform_device.h>

struct att_dev{
	struct platform_device *pdev;
	struct kobject *kobj;
};

static ssize_t att_store(struct device *dev, 
					struct device_attribute *attr, 
					const char *buf, size_t count) 
{
	printk("echo debug buf\n");

	return count;
}

static ssize_t att_show(struct device *dev,
                 struct device_attribute *attr,
                 char *buf)
{
	printk("cat debug buf\n");
	return 0;
}
static DEVICE_ATTR(test,0777,att_show,att_store);

static struct att_dev *dev = NULL;

static __devinit int att_probe(struct platform_device *ppdev){
	int ret;
	
	dev->kobj = kobject_create_and_add("attkobj", NULL); 
	if(dev->kobj == NULL){
		ret = -ENOMEM;
		goto kobj_err;
	}

	ret = sysfs_create_file(&dev->pdev->dev.kobj,&dev_attr_test.attr);
	if(ret < 0){
		goto file_err;
	}
	return 0;

file_err:
	 kobject_del(dev->kobj);  
kobj_err:
	return ret;
}

static struct platform_driver att_driver = {
	.probe = att_probe,
	.driver = {
		.owner = THIS_MODULE,
		.name = "att_test",
	},
};

static int __init att_init(void)
{
	int ret;

	dev = kzalloc(sizeof(struct att_dev),GFP_KERNEL);
	if(dev == NULL){
		printk("%s get dev memory error\n",__func__);
		return -ENOMEM;
	}
	
	dev->pdev = platform_device_register_simple("att_test", -1, NULL, 0);  
	if(IS_ERR(dev->pdev)){
		PTR_ERR(dev->pdev); 
		printk("%s pdev error\n",__func__);
		return -1;
	}

    ret = platform_driver_register(&att_driver);
    if(ret < 0){
        printk("%s register driver error\n",__func__);
        return ret;
    }

	return 0;
}

static void __exit att_exit(void)
{
	
}

module_init(att_init);
module_exit(att_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("driverSir");

Makefile原代码:

ifeq ($(KERNELRELEASE),)
#KERNEL_DIR:=/lib/modules/$(shell uname -r)/build/
KERNEL_DIR:=/usr/src/linux-headers-3.2.0-29-generic-pae
PWD:=$(shell pwd)
modules:
    $(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules
modules_install:
    $(MAKE) -C $(KERNEL_DIR) M=$(PWD) modules_install
clean:
    rm -rf  .*.cmd *.ko  *.o modules.order  Module.symvers *mod.c
.PHONY: modules modules_install clean
else
    modules-objs := att.o
    obj-m := att.o
endif


安装之后/sys/devices/platform/att_test/test

echo 1 > test 

cat test

dmesg之后会看到内核打印出

[  424.793357] echo debug buf
[  427.122139] cat debug buf

说明在echo 1 > test 时调用了att_store,cat test 的时候调用了att_show

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值