简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM