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

2290阅读 0评论2021-03-22 fangdikui
分类:LINUX


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


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
#include
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.o
KERNELDIR := /lib/modules/3.13.11-ckt39/build
PWD := $(shell pwd)
 
modules:
    $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
 
modules_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
错误,就在电脑的开机启动项中关闭安全启动模式即可。
————————————————
版权声明:本文为CSDN博主「火车上遇见」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/WAN_EXE/article/details/52770149
上一篇:打印机驱动程序设计---PCL指令汉字打印应用
下一篇:没有了