Linux内核模块开发之helloworld

2019-07-12 20:52发布

第一步、编写helloworld.c#include //所有模块都必须包含的头文件 
#include //一些宏定义,例如这里的KERN_INFO

#define DRIVER_AUTHOR "xz@vi-chip.com.cn"
#define DRIVER_DESC   "A sample driver"  

static int __init hello_init(void)
{
    printk(KERN_INFO "Hello world! ");//前面的宏表示打印的级别  

    return 0;
}

static void __exit hello_exit(void)
{
    printk(KERN_INFO "hello exit! ");
}

module_init(hello_init);//用宏来指定入口,加载模块时里面的加载函数会被调用  
module_exit(hello_exit);//模块的许可证 
MODULE_LICENSE("GPL");
//模块的作者
MODULE_AUTHOR(DRIVER_AUTHOR);
//模块的描述
MODULE_DESCRIPTION(DRIVER_DESC);第二步、编写Makefileifeq ($(KERNELRELEASE),)
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:                               
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules   
clean:                                             
        $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
else
    obj-m := helloworld.o
endif第三步、编译执行make all第四步、执行insmod helloworld.ko第五步、执行lsmod查看安装的内核模块第六部、查看输出的消息,执行命令dmesg Hello world!
第七步、卸载模块,执行rmmod helloworld,并查看输出的消息,执行命令dmesghello exit!
第八步、清除编译,执行make clean操作,清除执行make all操作生成的文件