您的位置:首页 > 运维架构 > Linux

Linux编写新的系统调用(内核版本3.2.18)

2012-05-27 10:10 363 查看
    Linux内核的lab2,菜鸟的尝试,有错误还望大牛们指正。

    感谢cffde同学的资料做参考:http://cffde.ineyes.org/old/content/tec_artle_12031001.html

    这里用的是3.2.18版本,稍微有一些变化。

    前期准备

    1 从http://www.kernel.org下载新内核,现在已经出了3.4的版本,但由于3.4的版本里面文件结构变化太大,所以还是选择3.2.18的稳定版本。

    2 解压压缩包,并移动至”/usr/src”目录下,此处需要root权限。

mv linux-3.0.23.tar.bz2 /usr/src/
tar -jxvf linux-3.0.23.tar.bz2


    正式添加系统调用

    1 添加新的系统调用,进入内核根目录

cd linux-3.0.23/kernel
   

    2 打开sys.c源文件,添加一个文件头

#include <linux/linkage.h>
   

    3 在文末添加函数的实现代码

asmlinkage int sys_helloworld(){
printk(KERN_EMERG "hello world!(by jesusjzp,2012 ============ >< ===========)");
return 1;
}
  

    4 修改系统调用的指针列表

cd ../arch/x86/kernel
gedit syscall_table_32.S
   

    5 打开syscall_table_32.S,在文末添加

.long sys_helloworld        /*223*/


    6 将工作目录置于”/usr/src/linux-3.0.23/arch/x86/include/asm”

gedit unistd_32.h


    7 打开unistd_32.h文件,在”#define __NR_**    ***”最末位置添加

#define __NR_helloworld     223


    编译内核:

    1 进入内核文件的根目录

cd ../../../..


    2 安装编译所需软件

apt-get install build-essential kernel-package libncurses5-dev fakeroot


    3 开始编译

make mrproper
## 此命令可选。当编译出错需要重新编译或不是第一次编译,都需要执行该命令清理编译历史 ##
make menuconfig
## 出现对话框时,可选择编译配置的模块,具体哪些模块可以删去,可参考http://blog.sina.com.cn/s/blog_62aa1a6d0100g35h.html ##
make -j8
## 编译内核命令,-j8用于四核处理器,即2核*2 ##


    4 安装内核,注:无需设置grub启动项,新版本的内核安装已经实现了这一步

make modules_install
make install


    检测系统调用

    1 编写测试代码

#include<stdio.h>

int main()
{
int tmp;
tmp=syscall(223);
printf("\n");
if(tmp==1)
{
printf("系统调用成功=================>>!\n");
}
}
   

    2 检测代码

gcc t.c
./a.out
dmesg –c  # 需要root权限


  3 执行结果

...
...
[   28.025069] EXT4-fs (loop0): re-mounted. Opts: errors=remount-ro,commit=0
[   37.884360] keyboard: can't emulate rawmode for keycode 240
[   37.884371] keyboard: can't emulate rawmode for keycode 240
[   37.884377] hp_wmi: Unknown key code - 0x20000
[  754.454039] hello world!(by jesusjzp,2012 ============ >< ===========)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息