目的:

1. 驱动热身。网上有很多类似的文章可供参考。

2. 在操作系统中, 编写这个设备的驱动。

3. 为写qemu的watchdog驱动练手。

有朋友问make的 watchdog驱动 需要什么准备,所以写这个blog。

环境:

ubuntu 12.04.4

热身:

  首先编写一个简单的 hello world驱动。

耗时(基于熟悉linux环境和操作系统的条件下):

  1. 安装操作系统 30-60分钟。

  2. 配置操作系统 30分钟。主要是配置中文书法。无其他特殊的配置。

  3. 代码编写运行 40分钟。

查看自己的内核版本:

Search for kernel version (optional)(搜寻内核的版本)

Type the following command:

$ apt-cache search linux-headers-$(uname -r)

Install linux-header package under Debina or Ubuntu Linux(更新内核的版本)

Type the following command:

$ sudo apt-get install linux-headers-$(uname -r)

代码:

// hello.c的驱动程序:
 
#include<linux/init.h>  //初始换函数
#include<linux/kernel.h>  //内核头文件
#include<linux/module.h>  //模块的头文件
 
MODULE_LICENSE("shaohef  BSD/GPL");
 
static int __init hello_start(void)
{
    printk(KERN_ALERT "Loading hello module...\n");
    printk(KERN_ALERT "Hello world\n");
    return 0;
}
 
static void __exit hello_end(void)
{
    printk(KERN_ALERT "Goodbye Mr.\n");
}
module_init(hello_start);
module_exit(hello_end);
// makefile文件:
ifeq ($(KERNELRELEASE),)
 KVERSION = $(shell uname -r)
all:
 make -C /lib/modules/$(KVERSION)/build M=$(shell pwd) modules
clean:
 make -C /lib/modules/$(KVERSION)/build M=$(shell pwd) clean
modules_install
 $(MAKE)  -C  $(KERNELDIR)M=$(PWD)  modules_install
else
 obj-m :=hello.o
endif
 

安装驱动(可能需要重启):

编译

$ make

挂载驱动

$ sudo insmod hello.ko

卸载驱动

$ sudo rmmod hello

查看驱动, 最好加上管道 |more指令 或者|grep

lsmod |grep hello

系统启动的时加载模块

文件 /etc/modules 设置加载的内核,这个文件里包含了系统启动的时候要加载的模块,每一个模块一行。

首先 hello 模块 拷贝到 /lib/modules/$(uname -r)/kernel/drivers.

建议的步骤:

(a)为 hello 模块建立一个目录

$ sudo mkdir -p /lib/modules/$(uname -r)/kernel/drivers/hello

(b)拷贝模块

$ sudo cp hello.ko /lib/modules/$(uname -r)/kernel/drivers/hello/

(c)编辑 /etc/modules 文件

$ sudo vim /etc/modules

加上下面一行

hello

(d)重启查看是否加载。

$ sudo cat /proc/modules

或者

$ sudo lsmod | less

查看程序的输出:

#cat   /var/log/syslog  |grep  world

如果syslog没有输出, 查看 /var/log/message 里面的信息

# tail -f /var/log/message

注:

insmod的本质就是将ko文件与运行的内核进行链接的过程。类似于编译helloworld的链接过程。

链接必然需要先进行编译,以便确定所需的外部符号(EXPORT_SYMBOLS)是否存在,因为有些符号(函数或全局变量)在内核中。在驱动中如果使用到这些符号,必须预留一个位置,insmod时进一步确定这些符号的具体位置(符号绑定)。

如果内核都没有编译过,怎么知道这些符号有没有编入内核中

最新文章

  1. SQL 对时间的处理
  2. 《BI那点儿事》Microsoft 时序算法——验证神奇的斐波那契数列
  3. 原生js写的贪吃蛇网页版游戏特效
  4. BZOJ3052——糖果公园
  5. 通过WinForm控件创建的WPF控件无法输入的问题
  6. fluery算法
  7. svn分支管理进行迭代开发
  8. DataTable使用总结
  9. java中对map使用entrySet循环
  10. wapPush
  11. Android学习总结——Popup menu:弹出式菜单
  12. PhpStorm创建Drupal模块项目开发教程(5)
  13. 更改pip源
  14. SSL 通信原理及Tomcat SSL 双向配置
  15. Python open()
  16. java注释中使用注解@see
  17. redis基础篇
  18. uart通讯协议
  19. python -- 面向对象三大特性
  20. 使用css制作倒影

热门文章

  1. In Depth : Android Boot Sequence / Process
  2. laravel5.1框架简介及安装
  3. 转:JavaScript函数式编程(三)
  4. 各种HelloWorld
  5. WebView cookies清理
  6. docker 私有仓库内容
  7. java应用程序远程登录linux并执行其命令(ssh jar包)
  8. 将Controller中的数据传递到View中显示
  9. #include &lt;string.h&gt;
  10. foj 2150 Fire Game(bfs暴力)