我想在 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 );
....
我得到这个 错误:初始化元素不是恒定 的,这让我意识到我必须做一些真正错误的事情,但是尽管我搜索我找不到任何东西,而且我无法通过查看其他实现来弄清楚如何做到这一点在内核中...
有人可以指出我正确的方向,可能有一个实际的例子吗?