hello_world-2.0之sys文件系统kobj

               hello_world-2.0之sys文件系统kobj

1.helloworld.c的源码

#include<linux/init.h>
#include<linux/module.h>
#include<linux/kobject.h>
#include<linux/sysfs.h>
#include<linux/string.h>


static int hello_value;




static ssize_t hello_show(struct kobject *kobj, struct kobj_attribute *attr,
                          char *buf)
{
   return sprintf(buf, "%d\n",hello_value);


}


static ssize_t hello_store(struct kobject *kobj, struct kobj_attribute *attr,
                           const char *buf, size_t count)
{
   sscanf(buf, "%du", &hello_value);
   return count;
}
static struct kobj_attribute hello_value_attribute = __ATTR(hello_value,0666,hello_show,hello_store);
static struct kobject *helloworld_kobj;


static int __init helloworld_init(void)
{
   int retval;
   helloworld_kobj = kobject_create_and_add("helloworld",kernel_kobj);
   if(!helloworld_kobj)
      return -ENOMEM;
   retval = sysfs_create_file(helloworld_kobj,&hello_value_attribute);
   if(retval)
      kobject_put(helloworld_kobj);
   return retval;
}


static void __exit helloworld_exit(void)
{
   kobject_put(helloworld_kobj);


}
module_init(helloworld_init);
module_exit(helloworld_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("[email protected]");


2.运行结果


root@thiz:/sys/kernel/helloworld# ls
hello_value

root@thiz:/sys/kernel/helloworld# echo 1 > hello_value

root@thiz:/sys/kernel/helloworld# cat hello_value 
1

3.分析

3.1 对于kobj有三方面:
(1)。目录项(/sys/kernel/helloworld),这个通过函数 kobject_create_and_add("helloworld",kernel_kobj);,可以在/sys下建立一个一个helloworld的目录项
(2).属性文件(hello_value),建立一个属性文件函数: sysfs_create_file(helloworld_kobj,&hello_value_attribute);这个同时也是建立了文件与操作之间的联系和对应
(3).操作( hello_show和hello_store):在sys系统中对文件的操作有一个函数:一个是show,一个是store;这个和普通的文件操作read和write有点类似,是他们的精简版。对于
ssprint和sscanf是对copy_from_user和copy_to_user函数的封装,指的是写内容到文件中。

如果是一组属性则可以
static struct attribute *attrs[] = {
        &foo_attribute.attr,
        &baz_attribute.attr,
        &bar_attribute.attr,
        NULL,   /* need to NULL terminate the list of attributes */
};
............................

static struct attribute_group attr_group = {
        .attrs = attrs,
};
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值