Search code examples
linuxkernelinsmod

insmod lkm.ko calls cleanup_module instead of init_module in loadable kernel module


I'm trying to make my first loadable kernel module on debian wheezy 7.5. I tried out some sample code from different tutorials on the web, but it doesn't work for me like I think it should be.

Here's my code:

#include <linux/module.h>
#include <linux/kernel.h>

void cleanup_module(void)
{
    printk(KERN_INFO "exit LKM...");
}

int init_module(void)
{
    printk(KERN_INFO "loading LKM...");
    return 0;
}

and I'm compiling it with a Makefile looking like this

obj-m += lkm.o
all:
    sudo make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

So it compiles just fine, but when I load the LKM with "$ sudo insmod lkm.ko" and then look into the log messages, it gives back "exit LKM...", so it seems like insmod calls the cleanup_module system call instead of the init_module. The same thing happens, when I use "$ sudo rmmod lkm", I get back "loading LKM.." in the log messages. So I really don't know why this is, and all I found on the web is, that insmod loads the LKM via init_module() and so on...

I'd appreciate some help or explanation for that, since I really have no clue what went wrong.

Thanks


Solution

  • Put newlines aka \n at the end of your printk strings.

    The problem you are seeing is caused by delayed printing. I bet that the first time you ran the insmod, you didn't see any output at all. Then you did some other things and then you unloaded the module. At that point, the buffer flushed out the previous message, causing it to LOOK as if it printing the init message during unload.

    What was actually happening was the kernel was saving up the line in order to output a complete line once it saw a newline. That newline didn't arrive until later.