首页 > 解决方案 > Linux内核模块中定义的特性可以用于内核代码吗?

问题描述

我可以在模块上使用内核代码的功能或使用 EXPORT_SYMBOL 的其他代码。

相反,我想在内核代码中使用 EXPORT_SYMBOL 使用内核模块的功能。

我有什么选择吗?

标签: linuxfunctionkernelkernel-module

解决方案


加载内核时,加载程序应该解析内核使用的每个符号(函数)。

因为内核加载时内核模块不可用,内核不能直接使用模块中定义的符号。

但是,内核内核可以有一个指针,它可以在加载时由模块的代码初始化。这可以被视为某种注册过程:

foo.h

// Header used by both kernel core and modules

// Register 'foo' function.
void register_foo(int (*foo)(void));

foo.c

// compiled as a part of the kernel core
#include <foo.h>

// pointer to the registered function
static int (*foo_pointer)(void) = NULL;

// Implement the function provided by the header.
void register_foo(int (*foo)(void))
{
  foo_pointer = foo;
}
// make registration function available for the module.
EXPORT_SYMBOL(register_foo);

// Calls foo function.
int call_foo(void)
{
  if (foo_pointer)
    return foo_pointer(); // call the registered function by pointer.
  else
    return 0; // in case no function is registered.
}

模块.c

// compiled as a module
#include <foo.h>

// Implement function
int foo(void)
{
  return 1;
}

int __init module_init(void)
{
   // register the function.
   register_foo(&foo);
   // ...
}

推荐阅读