您的位置:首页 > 编程语言 > C语言/C++

内核程序的基本框架

2017-09-11 14:59 288 查看

应用程序的基本框架

#include <stdio.h> //标准C库的头文件
//main 就是程序的入口函数
int main (void)
{
printf ("...\n"); //标准C的库函数
return 0; //程序的出口
}


内核kernel程序的基本框架

vim helloworld.c

#include <linux/init.h>
#include <linux/module.h>
static int helloworld_init (void)
{
printk ("hello, world\n");
return 0;
}
static void helloworld_exit(void)
{
}
module_init(helloworld_init);
module_exit(helloworld_exit);
MODULE_LICENSE("GPL");


代码总结

1.内核程序使用的头文件位于内核源码中,而不是标准C的头文件!

所以编译内核程序时,需要用到内核源码。

2.static int helloworld_init (void)

{

return 0;

}

此函数为程序的入口函数;

内核要求形参为void

返回值的数据类型为int

如果执行成功返回0,执行失败返回负值;

*问:如何判断此函数为入口函数呢?

答: 通过module_init宏进行修饰,告诉内核修饰函数就是入口函数

module_init (helloworld_init);*

3.static void helloworld_exit(void) { }

此函数为内核程序的出口函数

*问:如何判断此函数为出口函数?

答:通过module_exit宏进行修饰,告诉内核此函数为程序的出口函数 module_exit (helloworld_exit);*

4.内核打印信息用printk, 此函数的定义不是在标准C库中,而是在内核源码中!

同样在编译内核程序需要利用内核源码!

5.MODULE_LICENSE(“GPL”);

内核程序必须一律添加此句! 告诉内核此程序同样遵循GPL协议!

案例

编写第一个内存程序实施步骤

1.mkdir /opt/drivers/1.0 -p

2.cd /opt/drivers/1.0

3.vim helloworld.c

添加如下内容:

#include <linux/init.h>
#include <linux/module.h>
static int helloworld_init(void)
{
printk("hello,world!\n");
return 0;
}
static void helloworld_exit(void)
{
printk("goodbye,world!\n");
}
module_init(helloworld_init);
module_exit(helloworld_exit);
MODULE_LICENSE("GPL");


4.保存退出

*问:如何编译内核程序?

答:

明确:编译内核程序需要利用内核源码*

5.编写Makefile文件进行编译内核程序

Makefile语法:

目标: 依赖

TAB键 编译命令

vim Makefile,添加如下内容:

obj-m += helloworld.o #将helloworld.c编译生成最终的二进制可执行文件helloworld.ko

all:

make -C /opt/kernel SUBDIRS=$(PWD) modules#到内核/opt/kernel源码中进行make编译,然后告诉内核, 在你的源码以外还有一个目录/opt/drivers/1.0, 在这个目录下有一个.c文件需要你进行编译,要把它编译生成.ko文件

clean:

make -C /opt/kernel SUBDIRS=$(PWD) clean


6.执行make 进行编译

结果是: helloworld.c -> helloworld.ko

7.拷贝可以执行程序helloworld.ko到开发板上

cp helloworld.ko /opt/rootfs

8.问:如何让helloworld.ko中运行在内核kernel中

答:利用内核程序操作相关的命令

insmod = insert + module

作用:加载内核程序到kernel,内核程序开始运行

此时内核执行其入口函数helloworld_init ,如果入口函数执行成功(返回0),此程序永远运行在内核中,否则(返回负值)运行停止!

用法:insmod helloworld.ko

lsmod = list + module

作用:查看当前kernel中有哪些正在运行的程序

用法: lsmod

rmmod = remove + module

作用:删除指定的内核程序 ,此时内核会执行其出口函数 一旦删除,kernel中不会再有此程序

用法:rmmod helloworld
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息