Linux Module Stacking Example
What is module stacking?
New modules using the symbols exported by old modules.
Examples of modules stacking in Linux Kernel?
- Msdos filesystem relies on symbols exported by fat module
- Parallel port printer driver (lp) relies on symbols exported by generic parallel port driver (parport)
Let's write a sample device driver code which exports a function myadd performing addition of two numbers:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <linux/kernel.h> | |
#include <linux/module.h> | |
MODULE_LICENSE("GPL"); | |
int myadd(int a, int b) | |
{ | |
pr_info("%s: Adding %d with %d\t Result:%d\n", | |
__func__, a, b, a+b); | |
return a+b; | |
} | |
EXPORT_SYMBOL(myadd); | |
static int module1_init(void) | |
{ | |
pr_info("%s: In init\n", __func__); | |
return 0; | |
} | |
static void module1_exit(void) | |
{ | |
pr_info("%s: In exit\n", __func__); | |
} | |
module_init(module1_init); | |
module_exit(module1_exit); |
Code:
Now, we will write another module which uses the exported function:
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <linux/kernel.h> | |
#include <linux/module.h> | |
MODULE_LICENSE("GPL"); | |
extern int myadd(int a, int b); | |
static int module2_init(void) | |
{ | |
pr_info("%s: In init\n", __func__); | |
pr_info("%s: Add:%d\n", __func__, myadd(3, 5)); | |
return 0; | |
} | |
static void module2_exit(void) | |
{ | |
pr_info("%s: In exit\n", __func__); | |
} | |
module_init(module2_init); | |
module_exit(module2_exit); |
Makefile to Compile two modules:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
obj-m := module1.o | |
obj-m += module2.o | |
all: | |
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules | |
clean: | |
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean |
Comments
Post a Comment