操作系统实验一(题目1)

实验一 (题目一)


简要

  • 笔者的虚拟机装的是Ubuntu
  • 安装vim,make,gcc
  • 执行insmod命令时要用管理权限,sudo insmod mod
  • task_struct的state这个变量不知道是怎么回事,我的编译会出错,错误内容是没有这个模块成员???(哪个坏家伙把state换了), 改成_ _state就可以了
  • 以下附上本实验要用的task_struct成员,其中comm指进程名称,mm用于区分是否是内核线程

模块一

按照书上说明做即可


模块二

这里重点提示一下下,父节点的children节点和子节点的sibling节点,他们的关系是父节点的children节点与子节点的sibling节点构成了一个循环链表,所以求兄弟节点的if语句就是去掉children这个头节点,不然会有乱码



附代码

模块1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<linux/init.h>
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/sched/signal.h>

static int print_kernel_thread_init(void)
{
struct task_struct *p= NULL;
printk("module1 start");
for_each_process(p){
if(p->mm==NULL)
{
printk("%s\t%d\t%d\t%ld\t%d\n",p->comm,p->pid,p->parent->pid,p->__state,p->prio);
}
}
printk("finish");
return 0;
}

static void print_kernel_thread_exit(void)
{
printk("module1 exit");
}

module_init(print_kernel_thread_init);
module_exit(print_kernel_thread_exit);
MODULE_LICENSE("GPL");

Makefile

1
2
3
4
5
6
7
8
9
1 obj-m :=mod1.o
2 mod1-objs :=module1.o
3 KDIR :=/lib/modules/$(shell uname -r)/build
4 PWD :=$(shell pwd)
5 default:
6 make -C $(KDIR) M=$(PWD) modules
7 clean:
8 make -C $(KDIR) M=$(PWD) clean
9

模块2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<linux/init.h>
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/pid.h>
#include<linux/types.h>
#include<linux/sched.h>
#include<linux/list.h>
#include<linux/moduleparam.h>

static int pid;
module_param(pid,int ,0644);

static int print_fml_init(void)
{
struct pid* npid;
struct task_struct* task;
struct task_struct* parent;
struct task_struct* children;
struct task_struct* nsibling;
struct list_head* p;

npid=find_get_pid(pid);
task=pid_task(npid,PIDTYPE_PID);
printk(" mod1_1 start\n");

//parent
printk("Parent:\n");
parent=task->parent;
printk("%s\t %d\t %d\n",parent->comm,parent->pid,parent->__state);

//sibling
printk("Sibling:\n");
list_for_each(p,&(task->sibling)){
if(p!=&(task->parent->children)){
nsibling=list_entry(p,struct task_struct,sibling);
printk("%s\t %d\t %d\n",nsibling->comm,nsibling->pid,nsibling->__state);
}
}

//children
printk("Children:\n");
list_for_each(p,&(task->children)){
children=list_entry(p,struct task_struct,sibling);
printk("%s\t %d\t %d\n",children->comm,children->pid,children->__state);
}

return 0;
}

static void print_fml_exit(void){
printk("mod1_1 exit\n");
}

module_init(print_fml_init);
module_exit(print_fml_exit);

MODULE_LICENSE("GPL");

Makefile

1
2
3
4
5
6
7
8
1 obj-m :=mod1_1.o
2 mod1_1-objs :=module1_1.o
3 KDIR :=/lib/modules/$(shell uname -r)/build
4 PWD :=$(shell pwd)
5 default:
6 make -C $(KDIR) M=$(PWD) modules
7 clean:
8 make -C $(KDIR) M=$(PWD) clean

author: YaoGuangMing 2022-HDU

转载请标明出处!