如何在一个 linux 内核模块中定义一个函数并在另一个内核模块中使用它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9820458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define a function in one linux kernel module and use it in another?
提问by Ricardo
I developed two simple modules to the kernel. Now i want to define a function in one module and after that use it in the other.
我为内核开发了两个简单的模块。现在我想在一个模块中定义一个函数,然后在另一个模块中使用它。
How i can do that?
我怎么能这样做?
Just define the function and caller in the other module without problems?
只是在另一个模块中定义函数和调用者没有问题?
回答by cnicutar
Define it in module1.c
:
定义它module1.c
:
#include <linux/module.h>
int fun(void);
EXPORT_SYMBOL(fun);
int fun(void)
{
/* ... */
}
And use it in module2.c
:
并将其用于module2.c
:
extern int fun(void);
回答by Gopika BG
Linux kernel allows modules stacking, which basically means one module can use the symbols defined in other modules. But this is possible only when the symbols are exported. Let us make use of the very basic hello world module. In this module we have added function called "hello_export" and used the EXPORT_SYMBOL macro to export this function.
Linux 内核允许模块堆叠,这基本上意味着一个模块可以使用其他模块中定义的符号。但这只有在导出符号时才有可能。让我们使用非常基本的 hello world 模块。在此模块中,我们添加了名为“hello_export”的函数,并使用 EXPORT_SYMBOL 宏导出此函数。
hello_export.c
hello_export.c
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
printk(KERN_INFO "Hello,world");
return 0;
}
static hello_export(void) {
printk(KERN_INFO "Hello from another module");
return 0;
}
static void hello_exit(void)
{
printk(KERN_INFO "Goodbye cruel world");
}
EXPORT_SYMBOL(hello_export);
module_init(hello_init); module_exit(hello_exit); Prepare a Makefile ,Compile it using the "make" command and then insert it into the kernel using insmod. $insmod hello_export.ko All the symbols that the kernel is aware of is listed in /proc/kallsyms. Let us search for our symbol in this file.
模块初始化(hello_init);模块退出(你好退出);准备一个Makefile,使用“make”命令编译它,然后使用insmod将其插入内核。$insmod hello_export.ko 内核知道的所有符号都列在 /proc/kallsyms 中。让我们在这个文件中搜索我们的符号。
$ cat /proc/kallsyms | grep hello_export d09c4000 T hello_export[hello_export]
$ cat /proc/kallsyms | grep hello_export d09c4000 T hello_export[hello_export]
From the output we can see that the symbol we exported is listed in the symbols recognized by the kernel.
从输出中我们可以看到,我们导出的符号列在内核识别的符号中。