如何在两个Linux内核模块之间共享全局变量? [英] How can I share a global variable between two Linux kernel modules?

查看:406
本文介绍了如何在两个Linux内核模块之间共享全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在连接和断开USB时获得通知.因此,我正在尝试实施信号.我在debugfs中创建了文件"file1".然后,我提供了一个简单的写文件操作.

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.

在用户空间中有一个用户空间应用程序,该应用程序会将其PID写入debugfs的"file1"中.

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

在内核空间中,我可以使用上面提到的write方法获得传递的PID.但是我想在其他内核模块中使用此PID.因此,我尝试使用 EXPORT_SYMBOL(); ,但是如果不包括公共头文件,则会出现编译错误.如果包含头文件,则在刷新图像时,我会看到PID为'0'.

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'.

有人能告诉我,如果这是正确的方法吗?或告诉我我要去哪里错了.或者将PID写入文件时,是否可以在其他内核模块中获得通知.如果可以,怎么办?

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?

推荐答案

EXPORT_SYMBOL()是正确的方法.我不太理解如果我不包括公用头文件"的意思.听起来您好像在共享标头文件中包含了 EXPORT_SYMBOL(),这不是您想要执行的操作.您想要执行以下操作:

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(编译为module1.ko)

module1.c (compiles into module1.ko)

int my_exported_variable;

EXPORT_SYMBOL(my_exported_variable);

// The rest of module1.c

然后在module2.c中(编译为module2.ko,必须在module1.ko之后进行安装)

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

在插入第一个模块后,可以通过执行 grep my_exported_variable/proc/kallsyms 来检查符号是否已导出,假设您的计算机上有/proc/kallsyms 系统.如果您在该处看不到变量,则module2.ko的insmod将无法处理未解析的符号.

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.

这篇关于如何在两个Linux内核模块之间共享全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆