Linux驱动--为Ubuntu系统编写驱动程序入门

来源:互联网 发布:轩辕传奇辅助软件 编辑:程序博客网 时间:2024/05/18 16:19

先查看自己系统使用的内核版本:

wang@wang:~$ uname -r
3.13.0-96-generic

查看需要下载的源码包:

wang@wang:/usr/src$ apt-cache search linux-source
linux-source - Linux kernel source with Ubuntu patches
linux-source-3.13.0 - Linux kernel source for version 3.13.0 with Ubuntu patches

sudo apt-get install linux-source-3.13.0

下载完成之后,会在/usr/src目录下有一个linux-source-3.13.0.tar.bz2压缩包,进行解压。

root@wang:/usr/src#tar jxvf  linux-source-3.13.0.tar.bz2

开始配置内核选择最快的原版的配置(默认)方式:

root@wang:/usr/src/linux-source-3.13.0#make oldconfig

然后开始make,大约需要一个小时:

root@wang:/usr/src/linux-source-3.13.0#make

root@wang:/usr/src/linux-source-3.13.0#make bzImage

root@wang:/usr/src/linux-source-3.13.0#make modules

root@wang:/usr/src/linux-source-3.13.0#make mudules_install

make bzImage会在当前目录下生成vmlinux文件,重启系统,至此,内核树已经建立完成。

编写hello.c和Makefile文件

hello.c文件

#include <linux/init.h>#include <linux/module.h>MODULE_LICENSE("Dual BSD/GPL");static int hello_init(void){printk(KERN_ALERT "Hello, world\n");return 0;}static void hello_exit(void){printk(KERN_ALERT"Goodbye, cruel world\n");}module_init(hello_init);module_exit(hello_exit); 
Makefile文件

obj-m := hello.oKERNELDIR := /lib/modules/3.13.11-ckt39/buildPWD := $(shell pwd)modules:    $(MAKE) -C $(KERNELDIR) M=$(PWD) modulesmodules_install:    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install

(注意空格处是tab键)

编写完成后执行make操作:

wang@wang:~/test/test$ make

wang@wang:~/test/test$ ls

hello.c  hello.ko  hello.mod.c  hello.mod.o  hello.o  Makefile  modules.order  Module.symvers

加载模块:

root@wang:/home/wang/test/test# insmod hello.ko

卸载模块:

root@wang:/home/wang/test/test# rmmod hello.ko

查看效果:

root@wang:/home/wang/test/test2# cat /var/log/syslog | grep world
Oct  9 20:11:55 wang kernel: [ 1175.967987] Hello, world
Oct  9 20:13:22 wang kernel: [ 1262.909541] Goodbye, cruel world
Oct  9 20:46:38 wang kernel: [ 3259.997105] Hello, world
Oct  9 20:47:12 wang kernel: [ 3294.438485] Goodbye, cruel world

如果碰到

insmod error required key not available

错误,就在电脑的开机启动项中关闭安全启动模式即可。



0 0
原创粉丝点击