Linux设备驱动的编写与安装过程

来源:互联网 发布:刘德华唱功知乎 编辑:程序博客网 时间:2024/06/06 00:49

1.一个最简单的设备驱动

hello_module.c

#include <linux/init.h>#include <linux/module.h>MODULE_LICENSE("Dual BSD/GPL");//模块加载时调用的函数static int hello_init(void){//在终端输出Hello,只有在Linux终端下面才会输出,通过SSH等链接的终端不会输出        printk(KERN_ALERT "Hello!");        return 0;}//模块退出时调用的函数static void hello_exit(void){//在模块卸载时输出Bye        printk(KERN_ALERT "Bye!");}module_init(hello_init); //告诉内核在模块加载时,调用hello_initmodule_exit(hello_exit); //告诉内核在模块卸载时,调用hello_exit


2.如何编译模块

(1)、把hello_module.c放入linux源码目录中的driver/misc目录下;

(2)、修改driver/misc下的Makefile,在里面添加obj-m += hello_module.o;

(3)、输出make -C /usr/src/kernels/linux(linux源码的路径) SUBDIRS=/usr/src/kernels/linux/drivers/misc(设备驱动代码所在目录的路径) modules,其中-C的作用是在make的时候切换到制定的目录,make完以后再切回;

(4)、如果生成了hello _module.ko表明设备驱动模块编译成功了。

3.模块的安装与卸载

(1)、加载模块:insmod hello_module.ko,使用lsmod可以系统中所有已加载模块,如果看到有hello_module说明加载成功;

(2)、卸载模块:rmmod hello_module.ko。

至此,一个最简单的设备驱动已经可以投入使用。