完整的 Hello World 内核模块 hello.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("Dual BSD/GPL");

static int hello_init(void)
{
    printk(KERN_ALERT "Hello, world\n");
    return 0;
}

static void hello_exit(void)
{
    printk(KERN_ALERT "Goodbye, cruel world\n");
}

module_init(hello_init);
module_exit(hello_exit);

Makefile

1
2
3
4
5
6
7
8
9
obj-m +=hello.o

KDIR = /usr/src/linux-headers-3.19.0-21-generic

all:
	$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules

clean:
	rm -rf *.o *.ko *.mod.* *.symvers *.order

To run the code

1
2
3
4
5
$sudo insmod hello.ko
$dmesg
u will get the output
$sudo rmmod hello.ko
$dmesg