Ahmed Wael
Ahmed Wael

Reputation: 49

Initialization and Cleanup are swapped around in Kernel Module

Currently studying kernel modules, and we tasked with writing a small Hello World / Bye World kernel module (in C). Got the idea pretty quick and had a rough idea of what I should do.

Needed to make the initialization function print a Hello message, and the clean up function to print a Bye message. The initialization message should print when I add the kernel module to the list of modules (working on a Debian VM) using insmod, and the cleanup message should print when I remove the module using rmmod.

Here is a snippet of the code:

#define MODULE
#define LINUX
#define __KERNEL__

#include <linux/module.h>   // all modules
#include <linux/kernel.h>   // KERN_ALERT and potentially other priorities
#include <linux/init.h>     // macros

static int __init do_initialization(void) {
    printk(KERN_ALERT "Hello World :)");
    return 0;
}

static void __exit do_cleanup(void){
    printk(KERN_ALERT "Bye bye :)");
}

module_init(do_initialization);
module_exit(do_cleanup);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("A");
MODULE_DESCRIPTION("Exercise");
MODULE_VERSION("1.00");

This is the Makefile I use (this was provided to us but I understand most of it):

obj-m += mymodule.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

NB: I use KERN_ALERT instead of KERN_INFO just to make sure that it displays on my terminal regardless.

My problem lies in the following: When I run insmod mymodule.ko, the Bye Bye message is printed. When I run rmmod mymodule.ko, the Hello message is printed. It really doesn't make any sense to me, and I made sure that my functions are correctly set inside the macros.

Any help is appreciated.

Upvotes: 1

Views: 366

Answers (1)

Ahmed Wael
Ahmed Wael

Reputation: 49

As indicated by the link that Tsyvarev added as a comment to the question on 1st March 2021, and by the answer by Roi on 2nd March 2021, I simply needed to add \n when logging the kernel. Thank you to everyone who helped.

Upvotes: 1

Related Questions