完成 8.3 内核开发环境的搭建.
Signed-off-by: lion.chan <cy187lion@sina.com>
This commit is contained in:
parent
6d0b30d1b0
commit
9f61931e5f
|
@ -45,7 +45,7 @@ Linux 分为内核态和用户态,内核态为受保护的代码,用户态
|
|||
* 内核源码中会使用大量的高级 C 语言宏操作,有些代码比较绕,通常先知道其用途,再深入学习原理。
|
||||
* Linux 内核源码使用 Linux 代码风格进行开发,代码风格应共同遵守。
|
||||
|
||||
## 一个简单的 Linux 内核模块
|
||||
## hellodrv —— 一个简单的 Linux 内核模块
|
||||
|
||||
```cpp
|
||||
#include <linux/init.h>
|
||||
|
@ -60,7 +60,7 @@ static int hello_init(void)
|
|||
|
||||
static void hello_exit(void)
|
||||
{
|
||||
printk(KERN_ALERT "hello driver exit\n ");
|
||||
printk(KERN_ALERT "hello driver exit\n");
|
||||
}
|
||||
|
||||
module_init(hello_init);
|
||||
|
@ -90,20 +90,3 @@ all:
|
|||
clean:
|
||||
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
|
||||
```
|
||||
|
||||
该程序的编译和使用方式如下:
|
||||
|
||||
```bash
|
||||
make
|
||||
indmod hellodrv.ko
|
||||
lsmod
|
||||
rmmod hellodrv
|
||||
```
|
||||
|
||||
除可使用 indmod 命令加载模块外,还可以使用 modprobe 命令,该命令比 insmod 命令要强大,它在加载某模块时会同时加载该模块所依赖的其他模块。使用 modprobe 命令加载的模块若以:
|
||||
|
||||
```bash
|
||||
modprobe -r <module name>
|
||||
```
|
||||
|
||||
的方式卸载,将同时卸载其依赖的模块。
|
||||
|
|
|
@ -67,3 +67,66 @@
|
|||
![安装结束 02](./imgs/8.3_内核开发环境的搭建/018.png)
|
||||
|
||||
## 安装开发工具包
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install bison build-essential linux-headers-$(uname -r)
|
||||
```
|
||||
|
||||
## 安装虚拟机工具
|
||||
|
||||
依次点击菜单按钮 Devices -> Insert Guest Additions CD imags...,加载虚拟机工具磁盘镜像文件。
|
||||
|
||||
![安装虚拟机工具 01](./imgs/8.3_内核开发环境的搭建/019.png)
|
||||
|
||||
点击 Run 按钮进行安装,如安装未出现任何错误,并出现“Press Return to close this window...”字样时,可关闭窗口:
|
||||
|
||||
![安装虚拟机工具 02](./imgs/8.3_内核开发环境的搭建/020.png)
|
||||
|
||||
之后执行以下命令,这样在访问共享文件夹时可以不输入密码,然后重启:
|
||||
|
||||
```bash
|
||||
sudo gpasswd -a ${USER} vboxsf
|
||||
```
|
||||
|
||||
## 编译和测试 hellodrv 程序
|
||||
|
||||
完成以上步骤后,就可以在虚拟机中开发和验证内核驱动,以 [8.2 Linux 驱动开发概述中的 hellodrv 程序](./8.2_Linux_驱动开发概述.md) 为例,该程序的编译方法如下:
|
||||
|
||||
```bash
|
||||
make
|
||||
```
|
||||
|
||||
可使用 insmod 和 rmmod 加载和卸载模块:
|
||||
|
||||
```bash
|
||||
sudo insmod hellodrv.ko
|
||||
sudo rmmod hellodrv
|
||||
```
|
||||
|
||||
在 insmod 之后,可使用 lsmod 命令查看模块加载情况:
|
||||
|
||||
```bash
|
||||
$ lsmod
|
||||
Module Size Used by
|
||||
hellodrv 16384 0
|
||||
```
|
||||
|
||||
使用 dmesg 命令可打印 printk 的输出信息,验证 hellodrv 驱动程序的执行情况。
|
||||
|
||||
```bash
|
||||
$ dmesg
|
||||
[ 803.252552] hello driver enter
|
||||
[ 1009.245694] hello driver exit
|
||||
```
|
||||
|
||||
除可使用 insmod 命令加载模块外,还可以使用 modprobe 命令,该命令比 insmod 命令要强大,它会根据 modules.dep 中所描述的相依关系,决定要载入哪些依赖模块(modules.dep 文件由 depmod 命令生成)。使用 modprobe 命令加载和卸载模块的命令格式如下:
|
||||
|
||||
```bash
|
||||
# 加载模块
|
||||
modprobe <module name>
|
||||
# 卸载模块
|
||||
modprobe -r <module name>
|
||||
```
|
||||
|
||||
用 modprobe 卸载模块时,将同时卸载其依赖的模块。
|
||||
|
|
Binary file not shown.
After Width: | Height: | Size: 1.0 MiB |
Binary file not shown.
After Width: | Height: | Size: 136 KiB |
Loading…
Reference in New Issue