linux下增加一个新的系统调用实现pstree功能

来源:互联网 发布:软件测试的基本理论 编辑:程序博客网 时间:2024/05/24 15:36

这是我们linux课程的一个作业。
首先得到init进程的task_struct,根据list_for_each可以循环遍历可以的到其所有的子进程的 list_head,根据list_head使用list_entry可以得到其task_struct,在循环的同时,每得到一个进程的task_struct,就递归遍历其子进程的task_struct。在递归的同时,记录递归的深度,根据深度在每个子进程的pid前面加上相应多少的制表符,从而反应进程之间的父子关系。
代码:

int processtree(struct task_struct *p,int b) {       int dep=0;   //记录递归深度,根据深度决定在打印时候时进程pid前面添加几个制表符    struct list_head *head;        for(l=p->children.next;l!=&(p->children);l=l->next)//对父进程循环遍历其子进程    {             struct task_struct *t=list_entry(l,struct task_struct,sibling);//根据task_struct中list_head得到其task_struct结构体        while(dep!=0)        {            printk("\t | %d",dep);        //对于每个遍历到的进程,根据深度在其前边添加制表符        }        printk("---%d\n",p->pid);          //打印遍历到的当前进程,并打印出pid        dep+=(processtree(t,b+1)+1);      //对于遍历到的子进程,进行递归遍历他的子进程,同时遍历的深度加深           }    return dep;    }

实现方式:
根据所学知识,我们知道在内核中添加系统调用主要是修改系统调用表和实现系统调用函数,为此我下载了4.9版本的linux源码,在linux-4.9.9/Documentation/下找到了adding-sys.txt这个增加系统调用的说明文档,找到关键部分如图
这里写图片描述
对于x86平台,有个特别的说明:
这里写图片描述
在系统调用表下增加新的系统调用:
这里写图片描述
其中系统调用号是332.
更新kernel/sys_ni.c文件
这里写图片描述
最后在kernel/sys.c文件中实现新增加的函数:

int processtree(struct task_struct *p,int b) {       int dep=0;   //记录递归深度,根据深度决定在打印时候时进程pid前面添加几个制表符    struct list_head *head;        for(l=p->children.next;l!=&(p->children);l=l->next)//对父进程循环遍历其子进程    {             struct task_struct *t=list_entry(l,struct task_struct,sibling);//根据task_struct中list_head得到其task_struct结构体        while(dep!=0)        {            printk("\t | %d",dep);        //对于每个遍历到的进程,根据深度在其前边添加制表符        }        printk("---%d\n",p->pid);          //打印遍历到的当前进程,并打印出pid        dep+=(processtree(t,b+1)+1);      //对于遍历到的子进程,进行递归遍历他的子进程,同时遍历的深度加深           }    return dep;    }

makefile文件:
这里写图片描述

内核的编译:
首先下载linux源码,进入其目录
第一次编译由于没有安装ncurses库,会报错
安装ncurses
sudo apt-get install libncurses5-dev
生成内核配置文件
make menuconfig
如果是不是第一次配置,先运行make mrproper清除之前的配置,然后重新运行make menuconfig

这里写图片描述
这里写图片描述
直接选择退出,然后进行内核编译
make -j16
编译完成后,安装模块
make modules_install
make install
完成后重启
reboot

安装内核模块:
编译完成后,安装内核模块:
insmod file_name.ko
卸载内核模块:
rmmod file_name.ko

编写测试代码:
这里写图片描述

运行截图:
这里写图片描述
这里写图片描述

原创粉丝点击