现在的位置: 首页 > 综合 > 正文

Linux内核添加系统接口

2017年12月21日 ⁄ 综合 ⁄ 共 1530字 ⁄ 字号 评论关闭

linux版本:3.9.1

操作系统:unbuntu 12.04

1· 添加新接口定义。

修改文件:linux-***/arch/x86/kernel/syscall_32.c

在文件末尾追加如下代码

asmlinkage void sys_hellokernel(void)

{

printk(KERN_EMERG "hello kernel! i find you!");

}

2· 在系统接口列表中追加新系统接口入口

修改文件:linux-***/arch/x86/include/generated/asm/syscalls_32.h

eg. “__SYSCALL_I386(351, sys_hellokernel, sys_hellokernel)” (这之前系统调用最大的索引是350)

__SYSCALL_I386宏定义中第一个参数指定系统调用接口对应的索引

                                                 第二个参数就是系统调用接口

                                                 第三个参数在初始化系统调用列表时没有用到(暂时填写系统调用的函数名称)

内核提供一个特定大小的函数指针数组,上层调用系统接口时,根据提供的索引,从该数组中获取系统调用函数的地址,调用该接口函数。

指针数组大小就是syscalls_32.h中“__SYSCALL_I386(***)”的记录个数(__NR_syscall_max就是sizeof算出来的)

在添加系统接口是要保证__SYSCALL_I386中第一个参数的数值从0开始,连续递增(增幅为1),不要出现重复或不连续的情况(虽然这听起来是些废话)

2· 为新接口索引设定一个宏名称(这样根据索引调用接口时,代码更易读,方便记忆,同时也减少了内核修改对上层应用的影响)

修改文件:linux-***/arch/x86/include/generated/uapi/asm/unistd_32.h

eg. "define __NR_hellokernel 351"

3· 修改后就是编译,安装内核了。参考http://blog.csdn.net/instruction_number21/article/details/7922783

4· 启用新内核进入系统,编写测试程序,

#include<linux/errno.h>

#include<sys/syscall.h>

#include<linux/unistd.h>

void main()

{

syscall(351);

}

ps:我在将内核放到home下的工程文件夹中编译的,在程序中引用__NR_hellokernel时说未定义,

     不知道是什么情况,有了解的希望能指点一些,在次多谢了!

5· 编译执行测试程序

gcc hellokernel.c -o hellokernel

./hellokernel

6· 检查系统日志,看是否调用新接口

vim /var/log/syslog

搜索hellokernel找到“hello kernel! i find you!”就说明新接口被调用了

感谢网上分享知识的同学,感谢vim,ctags,vimgrep以及可爱的find。希望对大家有帮助!

参考资料:

1· 《操作系统概念》

2· http://www.linuxidc.com/Linux/2011-04/34079.htm

3· http://os.51cto.com/art/201001/176268.htm

http://blog.csdn.net/instruction_number21/article/details/7922783

5· http://www.cnblogs.com/zero1665/archive/2010/05/05/1728347.html

抱歉!评论已关闭.