0

我想在 linux 内核中使用用户可编辑的全局变量。那可能吗?这就是我使用源代码提供的示例想到的:

拱/x86/内核/foo.c

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

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);

包括/linux/foo.h

#ifndef FOO_H
#define FOO_H
extern unsigned int foo;
#endif

拱/x86/randomfile.c

#include <linux/foo.h>
....
int foobar = ( 12 + foo );
....

我得到这个 错误:初始化元素不是恒定 的,这让我意识到我必须做一些真正错误的事情,但是尽管我搜索我找不到任何东西,而且我无法通过查看其他实现来弄清楚如何做到这一点在内核中...

有人可以指出我正确的方向,可能有一个实际的例子吗?

4

1 回答 1

0

C 全局变量必须使用编译时已知的值进行初始化。foo不是。

作为一般规则,可以使用枚举值、数字常量和对其中任何一个的数学运算来初始化全局整数。例如,这是有效的:

enum foo_enum
{
    foo = 12
};

int foobar = (12 + foo);

foo但是,很明显,您只是失去了在运行时进行更改的能力。

如果在加载内核模块时调用了一个函数(那是__init- 标记的函数吗?),您可以在那里进行初始化。

于 2012-03-11T23:29:27.460 回答