Tuesday, November 2, 2021

[SOLVED] insmod printk doesn't work, but works for rmmod

Issue

Since I'm still learning about kernel module programming, unable to figure out the rational behind the issue. When I run insmod hello.ko, dmesg or /var/logs/message doesn't show/print the message, whereas when I run rmmod hello.ko, dmesg or /var/logs/message shows/print string from hello_init(void) and hello_exit(void).

#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");


static int hello_init(void)
{
    printk(KERN_ALERT "Hello World!!");
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "Bye World!");
}

module_init(hello_init);
module_exit(hello_exit);

Solution

printk is very newline aware. The printk(KERN_ALERT "Hello World!!"); doesn't print anything because it doesn't has a newline. It awaits the next printk(KERN_CONT as a continuation of the line and the next prinkt(KERN_CONT with a newline. It get's printed on the next printk(KERN_ALERT because then printk assumes that the last line has ended and prints it. If you want to output it immediately add a newline to the format string.

So just:

  printk(KERN_ALERT "Hello World!!\n");


Answered By - KamilCuk