Linux Kernel Module Code Implementation Your module will be defined in a file na
ID: 3814549 • Letter: L
Question
Linux Kernel Module Code Implementation
Your module will be defined in a file named km.c and do the following:
1.-When your kernel module is loaded it will print out to /var/log/messages the following message (verbatim):
"km loaded!"
2.-When the kernel module is removed it will print the following message (verbatim) in the same log file as above:
"km removed!"
3.-While loaded, your module will add the file km to the "proc" file system and act as an 'echo' file, anything written should be read back as it was written. I.e. if I do echo "This is a km test" > /proc/km and then do cat /proc/km, you should see the following text in the screen: "This is a km test". Further read from the file should find the file empty.
I am truly confused by this question. Can someone help me?
Explanation / Answer
Answer for Q1 and Q2 : Code for kernel module
/*
* km.c - The simplest kernel module.
*/
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
int init_module(void)
{
/*loads this message in the /var/log/messages when the kernel is loaded*/
printk(KERN_INFO "km loaded. ");
/*
* A non 0 return means init_module failed; module can't be loaded.
*/
return 0;
}
void cleanup_module(void)
{
/*loads this message in the /var/log/messages when the kernel is cleaned or deleted.
printk(KERN_INFO "km removed. ");
}
Kernel modules must have at least two functions:
a) A "start" (initialization) function called init_module() which is called when the module is insmoded into the kernel
b) An "end" (cleanup) function called cleanup_module() which is called just before it is rmmoded.
Every kernel module needs to include linux/module.h which is only used for the macro expansion for the printk() log level, KERN_ALERT
Compiling the kernel module :
obj-m += km.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
Now you can compile the module by issuing the command "make".
command : make
Kernel modules now have a .ko extension (in place of the old .o extension) which easily distinguishes them from conventional object files. Now to insert your freshly compiled module it into the kernel with insmod ./km.ko. All modules loaded into the kernel are listed in /proc/modules. Go ahead and cat that file to see that your module is really a part of the kernel.To remove your module from the kernel by using rmmod hello-1.
Now take a look at /var/log/messages just to see that it got logged to your system logfile.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.