由于工作的关系,之前从事过将近1年的linux内核模块开发,但是后来荒废掉了。

最近工作调整,需要重新捡起来。今天周六没加班,早上起来手里痒痒下定决心开始编写第一个模块。

闲话少说,直接上硬货。

hello.c

#include <linux/module.h>

#include <linux/kernel.h>

#include <linux/init.h>

 

static int __init hello_init(void)

{

    printk(KERN_INFO "hello kernel!\n");

    return 0;

}

 

static void __exit hello_exit(void)

{

    printk(KERN_INFO "bye kernel!\n");

}

 

module_init(hello_init);

module_exit(hello_exit);

 

MODULE_LICENSE("GPL");

MODULE_ATHOUR("XXX");

 

Makefile

ifneq (!(KERNELRELEASE),)

obj-m := hello.o

else

PWD := $(shell pwd)

KVER ?= $(shell uname -r)

KDIR := /lib/module/$(KVER)/build

 

all:

        $(MAKE) -C $(KDIR) M=$(PWD)

clean:

        rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions

endif

注意以root用户登录,helloc和Makefile放置在同1目录下

在提示符下输入make命令,则在当前目录中会生成hello.ko

下面就是我们熟悉的如何加/卸载ko了

执行insmod hello.ko命令,然后dmesg查询日志中是否有hello kernel信息

执行rmmod hello.ko命令,然后demsg查询日志中是否有bye kernel信息

 

我的环境是在虚拟机中安装centos6.5,其他版本未验证过,上述步骤仅供参考,有问题可以交流。