snifer

【原创】基于嵌入式系统的模块化编程的拓展

0
阅读(2087)

前面介绍了如何进行模块化编程,下面我写一写模块化编程的拓展,在上一个教程的基础上,加入module_initmodule_exit的支持,加载模块,观察结果。

/*
 * hello.c
 *
 * Simple hello world 2.6 driver module with module_init, module_exit
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>

MODULE_LICENSE ("GPL");

static int __init hello_2_init (void)
{
printk (KERN_INFO "Hello world\n");
return 0;
}

static void __exit hello_2_exit (void)
{
printk (KERN_INFO "Goodbye world\n");
}

module_init (hello_2_init);
module_exit (hello_2_exit);

然后:

$ su root

$ cp ex2-init-exit  /home/linux/test –a

2、$ cd /home/linux/test/ex2-init-exit

3、$ make

4、通过insmod命令将模块加入内核

$ insmod  insmod hello.ko

5、通过lsmod查看内核模块

$ lsmod | grep hello

6、通过rmmod删除内核中的模块

$ rmmod hello

7、查看源码,适当修改

模块化编程的好处我就不再赘述,非常好的思想。