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 bufn");
- return count;
- }
- static ssize_t att_show(struct device *dev,
- struct device_attribute *attr,
- char *buf)
- {
- printk("cat debug bufn");
- 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 errorn",__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 errorn",__func__);
- return -1;
- }
- ret = platform_driver_register(&att_driver);
- if(ret < 0){
- printk("%s register driver errorn",__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