How can I share a global variable between two Linux kernel modules?

我与影子孤独终老i 提交于 2021-02-16 09:00:32

问题


I am trying to get notification when USB is connected and disconnected. So I am trying to implement signals. I created a file "file1" in debugfs. Then I provided a simple write file operation.

In user space there is a user space application, which will write its PID in the "file1" of debugfs.

In kernel space I can get the PID passed using the write method mentioned above. But I want to use this PID in a different kernel module. So I tried using EXPORT_SYMBOL();, but if I don't include the common header file, I get a compilation error. If I include the header file, when I flash the image, I see that PID is '0'.

Can anybody tell me, if this the right way? Or tell me where am I going wrong. Or can I get notification in different kernel module when PID is written to the file. If so how?


回答1:


EXPORT_SYMBOL() is the correct approach. I do not quite understand what you mean by "if I don't include the common header file". It sounds like you are including the EXPORT_SYMBOL() in a shared header file which is not what you want to do. You want to do something like the following:

module1.c (compiles into module1.ko)

int my_exported_variable;

EXPORT_SYMBOL(my_exported_variable);

// The rest of module1.c

And then in module2.c (compiles into module2.ko which must be insmod-ed after module1.ko)

extern int my_exported_variable; // Note the extern, it is declaring but not defining it, the definition is in module1

// The rest of module2.c

After you insmod the first module you can check that the symbol is exported by doing a grep my_exported_variable /proc/kallsyms, assuming you have /proc/kallsyms on your system. If you don't see your variable there then the insmod of module2.ko will fail do to an unresolved symbol.



来源:https://stackoverflow.com/questions/31197345/how-can-i-share-a-global-variable-between-two-linux-kernel-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!