How can I use a sysfs kobject as a global variable?-Collection of common programming errors
I would like to use an user-editable global variable in the linux kernel. Is that possible? That’s what I came up with using the example provided with the source code:
arch/x86/kernel/foo.c
#include
#include
#include
#include
#include
int foo = 12;
static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%d\n", foo);
}
static ssize_t foo_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
sscanf(buf, "%du", &foo);
return count;
}
static struct kobj_attribute foo_attribute =
__ATTR(foo, 0666, foo_show, foo_store);
static struct attribute *attrs[] = {
&foo_attribute.attr,
NULL,
};
static struct attribute_group attr_group = {
.attrs = attrs,
};
static struct kobject *example_kobj;
static int __init example_init(void)
{
int retval;
example_kobj = kobject_create_and_add("kobject_example", kernel_kobj);
if (!example_kobj)
return -ENOMEM;
retval = sysfs_create_group(example_kobj, &attr_group);
if (retval)
kobject_put(example_kobj);
return retval;
}
static void __exit example_exit(void)
{
kobject_put(example_kobj);
}
module_init(example_init);
module_exit(example_exit);
include/linux/foo.h
#ifndef FOO_H
#define FOO_H
extern unsigned int foo;
#endif
arch/x86/randomfile.c
#include
....
int foobar = ( 12 + foo );
....
I get this error: initializer element is not constant which makes me realize I must be doing something really wrong, but as much as I search I can’t find anything and I can’t figure out how to do it from looking at other implementations in the kernel…
Could someone point me to the right direction, possibly with a practical example?