Linux驱动开发之编写第一个内核模块--Hello World

1. 在内核目录下新建一个目录如hello_world命令如下:

mkdir hello_world

2. 编写hello.c文件,源码如下:

/*
 * a simple kernel module: hello
 *
 * Copyright (C) 2020 xxx (xxxxx)
 *
 * Licensed under GPLv2 or later
 */
#include <linux/init.h>
#include <linux/module.h>

static int __init hello_init(void)
{
        printk(KERN_INFO "hello World enter\n");
        return 0;
}

module_init(hello_init);

static void __exit hello_exit(void)
{
        printk(KERN_INFO "hello World exit\n");
}
module_exit(hello_exit);

MODULE_AUTHOR("xx xx <xxxxx>");//作者
MODULE_LICENSE("GPS v2");//模块许可证声明,一般用GPL v2
MODULE_DESCRIPTION("A simple hello world module");//模块描述
MODULE_ALIAS("a simplest module"); //别名

3. 编写Makefile

KVERS = $(shell uname -r)

obj-m += hello.o

build: kernel_modules

kernel_modules:
        make -C /lib/modules/$(KVERS)/build M=$(CURDIR) modules

clean:
        make -C /lib/modules/$(KVERS)/build M=$(CURDIR) clean

4. 在hello_world目录下执行make命令

$ make
make -C /lib/modules/3.10.0Likaige+/build M=/home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world modules
make[1]: Entering directory '/home/LiKaige/kernel/2_linux-3.10'
  CC [M]  /home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world/hello.o
  Building modules, stage 2.
  MODPOST 1 modules
  CC      /home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world/hello.mod.o
  LD [M]  /home/LiKaige/kernel/2_linux-3.10/drivers/misc/hello_world/hello.ko
make[1]: Leaving directory '/home/LiKaige/kernel/2_linux-3.10'
$ ls *.ko
hello.ko
生成hello.ko文件

5. 常用的几个命令:

insmod hello.ko        //加载模块
rmmod hello.ko         //卸载模块
lsmod | grep hello     //查看模块是否运行及是否被使用
tail /var/log/messages //查看加载或卸载模块时内核打印的log
modinfo hello.ko       //查看内核模块参数,如author, license, description等

注意:以上几个命令都要用root权限
eg:

# insmod hello.ko 
# lsmod | grep hello
hello                    905  0 
# rmmod hello.ko 
# tail /var/log/messages
May 25 11:40:37 localhost kernel: hello World exit
May 25 11:40:43 localhost kernel: [  797.016662] hello World enter
May 25 11:40:43 localhost kernel: hello World enter
May 25 11:40:50 localhost journal: No devices in use, exit
May 25 11:40:58 localhost kernel: [  812.600537] hello World exit
May 25 11:40:58 localhost kernel: hello World exit
May 25 11:41:08 localhost kernel: [  821.954504] hello World enter
May 25 11:41:08 localhost kernel: hello World enter
May 25 11:41:10 localhost kernel: [  824.025106] hello World exit
May 25 11:41:10 localhost kernel: hello World exit

对应完整源码下载链接:
https://download.csdn.net/download/sinat_29891353/12456897

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章