Ubuntu 下编译一个简单Linux内核模块

hello.c

#include <linux/init.h>
#include <linux/module.h>

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);

MODULE_LICENSE("Daul BSD/GPL");

Makefile

obj-m := hello.o

KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

module:
	$(MAKE) -C $(KDIR) M=$(PWD) modules

clean:
	rm -rf *.o *.ko .depend *.mod o*.mod .c Module.* modules.* 

log

make 编译
hostname:~/Documents$ make 
make -C /lib/modules/4.4.0-148-generic/build M=/home/justin/Documents modules
make[1]: Entering directory `/usr/src/linux-headers-4.4.0-148-generic'
  CC [M]  /home/justin/Documents/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/justin/Documents/hello.mod.o
  LD [M]  /home/justin/Documents/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-4.4.0-148-generic'

编译后生成其它文件
hostname:~/Documents$ ls
hello.c   hello.ko     hello.mod.o  Makefile   modules.order
hello.c~  hello.mod.c  hello.o      Makefile~  Module.symvers

insmod 安装内核模块
hostname:~/Documents$ sudo insmod hello.ko
[sudo] password for justin: 

lsmod 查找模块是否安装成功
hostname:~/Documents$ lsmod | grep hello
hello                  16384  0 

rmmod 移除模块
hostname:~/Documents$ sudo rmmod hello.ko

查找内核打印函数 prink 输出的log
hostname:~/Documents$ cat /var/log/syslog | grep hello
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.776659] hello: loading out-of-tree module taints kernel.
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.776661] hello: module license 'Daul BSD/GPL' taints kernel.
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.776684] hello: module verification failed: signature and/or required key missing - tainting kernel


hostname:~/Documents$ cat /var/log/syslog | grep Hello
Mar 13 16:53:43 justin-virtual-machine kernel: [ 2084.778871] Hello, world
Mar 13 17:11:44 justin-virtual-machine kernel: [ 3165.723490] Hello, world


hostname:~/Documents$ cat /var/log/syslog | grep Good
Mar 13 16:54:24 justin-virtual-machine kernel: [ 2125.998689] Goodbye, cruel world
Mar 13 17:12:08 justin-virtual-machine kernel: [ 3190.646031] Goodbye, cruel world

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值