First, find the source that your current Linux kernel was compiled from. You can save the mymodule.c in any one of the folder under staging or drivers directory
mymodule.c
mymodule.c
#include <linux/module.h>
#include <linux/config.h>
#include <linux/init.h>
static int __init mymodule_init(void)
{
printk ("My module worked!\n");
return 0;
}
static void __exit mymodule_exit(void)
{
printk ("Unloading my module.\n");
return;
}
module_init(mymodule_init);
module_exit(mymodule_exit);
MODULE_LICENSE("GPL");
Edit the Makefile in the same directory. Add this line
obj-m += mymodule.o
Compile your module:
# make -C [top directory of your kernel source] SUBDIRS=$PWD modules
Load the module:
# insmod ./mymodule.oAnd check to see if your message printed out:# dmesgAt the end of the output:My module worked!Now remove the kernel module:# rmmod mymoduleCheck the output of dmesg again, you could see the output:Unloading my module.