module_init: when the module is loaded by the kernel
module_exit: when the module is removed from memory / unloaded
This part assumes that your module is a driver otherwise it is a matter of building your module outside the kernel directory, with the target destination set to the kernel source directory
update modules Makefile to include your module. e.g. the hello module lives in linux-4.15/drivers/hello/
Append the Makefile
in drivers/
with obj-m += hello/
Then append the Makefile
in hello/
with obj-m += hello.o
finally build with
$ make modules
as per the previous assignment, we can install the module with
$ make modules_install
not sure if 'installing the module' meant 'loading' so this is included for completeness sake
$ cd /lib/modules/4.15.0/kernel/drivers/hello/ #or where ever your install your module
$ insmod hello.ko
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
+ #include <linux/moduleparam.h>
MODULE_LICENSE("GPL");
+ static char *who = "world";
+ module_param(who, charp, S_IRUGO);
static int hello_init(void) {
- printk(KERN_ALERT "Hello, world\n");
+ printk(KERN_ALERT "Hello, %s\n", who);
return 0;
}
static void hello_exit(void) {
- printk(KERN_ALERT "Goodbye, cruel world\n");
+ printk(KERN_ALERT "Goodbye, %s\n", who);
}
module_init(hello_init);
module_exit(hello_exit);
Note: dmesg -c
was called prior to loading the module
$ mknod /dev/onebyte c 61 0
static ssize_t onebyte_read(struct file *filep, char __user *buf, size_t count, loff_t *f_pos) {
if (*f_pos + count > CAPACITY) {
count = CAPACITY - *f_pos;
}
if (copy_to_user(buf, onebyte_data, count) != 0) {
return -EFAULT;
}
*f_pos += count;
return count;
}
static ssize_t onebyte_write(struct file *filep, const char __user *buf, size_t count, loff_t *f_pos) {
if (*f_pos > CAPACITY) {
return 0;
}
if (copy_from_user(onebyte_data, buf, CAPACITY) != 0) {
return -EFAULT;
}
if (count > CAPACITY) {
return -ENOSPC;
}
return CAPACITY;
}
Commits log