当前位置: 首页 > news >正文

Lab4 【哈工大_操作系统】进程运行轨迹的跟踪与统计

本节将更新哈工大《操作系统》课程第四个 Lab 实验 进程运行轨迹的跟踪与统计。按照实验书要求,介绍了非常详细的实验操作流程,并提供了超级无敌详细的代码注释

实验目的:

  • 掌握 Linux 下的多进程编程技术;
  • 通过对进程运行轨迹的跟踪来形象化进程的概念;
  • 在进程运行轨迹跟踪的基础上进行相应的数据统计,从而能对进程调度算法进行实际的量化评价,更进一步加深对调度和调度算法的理解,获得能在实际操作系统上对调度算法进行实验数据对比的直接经验。

实验任务:

进程在其生命期中的运行轨迹实际上就表现为进程状态的多次切换,如进程创建以后会成为就绪态;当该进程被调度以后会切换到运行态;在运行的过程中如果启动了一个文件读写操作,操作系统会将该进程切换到阻塞态(等待态)从而让出 CPU;当文件读写完毕以后,操作系统会在将其切换成就绪态,等待进程调度算法来调度该进程执行……
1、基于模板 process.c 编写多进程的样本程序,实现如下功能: + 所有子进程都并行运行,每个子进程的实际运行时间一般不超过 30 秒; + 父进程向标准输出打印所有子进程的 id,并在所有子进程都退出后才退出;
2、在 Linux0.11 上实现进程运行轨迹的跟踪。 + 基本任务是在内核中维护一个日志文件 /var/process.log,把从操作系统启动到系统关机过程中所有进程的运行轨迹都记录在这一 log 文件中。
3、在修改过的 0.11 上运行样本程序,通过分析 log 文件,统计该程序建立的所有进程的等待时间、完成时间(周转时间)和运行时间,然后计算平均等待时间,平均完成时间和吞吐量。可以自己编写统计程序,也可以使用 python 脚本程序—— stat_log.py(在 /home/teacher/ 目录下) ——进行统计。
4、修改 0.11 进程调度的时间片,然后再运行同样的样本程序,统计同样的时间数据,和原有的情况对比,体会不同时间片带来的差异。

一、编写样本程序

编写 process.c 样本程序,实现函数模拟占用 CPU 和 I/O 时间

定义占用 CPU 和 I/O 时间函数:

/** 此函数按照参数占用 CPU 和 I/O 时间* last            :     函数实际占用CPU和I/O的总时间,不含在就绪队列中的时间,>=0是必须的* cpu_time        :     一次连续占用CPU的时间,>=0是必须的* io_time        :     一次I/O消耗的时间,>=0是必须的* 如果 last > cpu_time + io_time,则往复多次占用CPU和I/O* 所有时间的单位为秒*/
void cpuio_bound(int last, int cpu_time, int io_time)
{// tms 结构体记录 用户代码 和 内核代码 运行时间struct tms start_time, current_time;// 长整型,记录时钟滴答数clock_t utime, stime;int sleep_time;while (last > 0){/* CPU Burst */times(&start_time);/* 其实只有t.tms_utime才是真正的CPU时间。但我们是在模拟一个* 只在用户状态运行的CPU大户,就像“for(;;);”。所以把t.tms_stime* 加上很合理。*/do{times(&current_time);utime = current_time.tms_utime - start_time.tms_utime;    // 进程执行用户代码时间stime = current_time.tms_stime - start_time.tms_stime;    // 进程执行内核代码时间} while ( ( (utime + stime) / HZ )  < cpu_time );            // 得到时钟滴答次数,乘10ms得到真正的时间last -= cpu_time;                                            // 运行CPU后剩余时间if (last <= 0 )break;/* IO Burst *//* 用sleep(1)模拟1秒钟的I/O操作 */sleep_time=0;while (sleep_time < io_time){sleep(1);                            // 模拟 I/O操作 占用进程时间sleep_time++;}last -= sleep_time;                        // 运行 CPU + I/O 剩余时间}
}

创建多进程并调用占用时间函数

#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
#include <sys/types.h>#define HZ    100void cpuio_bound(int last, int cpu_time, int io_time);
/*
1.  所有子进程都并行运行,每个子进程的实际运行时间一般不超过30秒;
2.  父进程向标准输出打印所有子进程的id,并在所有子进程都退出后才退出;
*/
int main(int argc, char * argv[])
{pid_t n_proc[10]; /*10个子进程 PID*/int i;for(i=0;i<10;i++){n_proc[i] = fork();        // 父进程-返回子进程ID; 子进程-返回0/*子进程*/if(n_proc[i] == 0){cpuio_bound(20,2*i,20-2*i);     /*每个子进程都占用20s*/return 0;                         /*执行完cpuio_bound 以后,结束该子进程*/}/*fork 失败*/else if(n_proc[i] < 0 ){printf("Failed to fork child process %d!\n",i+1);return -1;}/*父进程继续fork, 此处为父进程 */pid_t father = getpid();        // 获得进程标志符printf("Now is the father's pid: %d\n", father);}/*打印所有子进程PID*/for(i=0;i<10;i++)printf("Child PID: %d\n",n_proc[i]);/*等待所有子进程完成*/wait(&i);  /*Linux 0.11 上 gcc要求必须有一个参数, gcc3.4+则不需要*/ return 0;
}

编译 process.c 样本程序

gcc -o myprocess process.c

二、维护日志文件

把从操作系统启动到系统关机过程中所有的进程运行轨迹都记录在log文件中

1、内核启动时就打开 process.log 文件

init/main.c 文件中添加如下代码:

//……
move_to_user_mode();/***************添加开始***************/
setup((void *) &drive_info);
(void) open("/dev/tty0",O_RDWR,0);    
(void) dup(0);        
(void) dup(0);        
(void) open("/var/process.log",O_CREAT|O_TRUNC|O_WRONLY,0666);
/***************添加结束***************/if (!fork()) {        /* we count on this going ok */init();
}
//……

其中 init() 函数建立了文件描述符 0、1 、2和/dev/tty0的关联,它们分别就是 stdinstdout 和 stderr。这三者的值是系统标准。仿照将把 log 文件的描述符关联到 3。此后 fork() 将会继承这些文件描述符

2、编写向 log 文件写函数 fprintk

在内核状态下无法直接使用write()函数向log文件输出,因此需要自己编写函数。参考了 printk() 和 sys_write() 而写成,向 kernel/printk.c 文件中添加如下函数:

#include "linux/sched.h"
#include "sys/stat.h"static char logbuf[1024];
int fprintk(int fd, const char *fmt, ...)
{va_list args;int count;struct file * file;struct m_inode * inode;va_start(args, fmt);count=vsprintf(logbuf, fmt, args);va_end(args);
/* 如果输出到stdout或stderr,直接调用sys_write即可 */if (fd < 3){__asm__("push %%fs\n\t""push %%ds\n\t""pop %%fs\n\t""pushl %0\n\t"/* 注意对于Windows环境来说,是_logbuf,下同 */"pushl $logbuf\n\t" "pushl %1\n\t"/* 注意对于Windows环境来说,是_sys_write,下同 */"call sys_write\n\t" "addl $8,%%esp\n\t""popl %0\n\t""pop %%fs"::"r" (count),"r" (fd):"ax","cx","dx");}else    
/* 假定>=3的描述符都与文件关联。事实上,还存在很多其它情况,这里并没有考虑。*/{/* 从进程0的文件描述符表中得到文件句柄 */if (!(file=task[0]->filp[fd]))    return 0;inode=file->f_inode;__asm__("push %%fs\n\t""push %%ds\n\t""pop %%fs\n\t""pushl %0\n\t""pushl $logbuf\n\t""pushl %1\n\t""pushl %2\n\t""call file_write\n\t""addl $12,%%esp\n\t""popl %0\n\t""pop %%fs"::"r" (count),"r" (file),"r" (inode):"ax","cx","dx");}return count;
}

使用示例:

// 向stdout打印正在运行的进程的ID
fprintk(1, "The ID of running process is %ld", current->pid); // 向log文件输出跟踪进程运行轨迹
fprintk(3, "%ld\t%c\t%ld\n", current->pid, 'R', jiffies); 
// 进程id、进程状态、滴答数(开机以来经历多少个10ms)

3、向状态切换点添加输出log文件代码

需要对 /kernel 文件夹下的 fork.c, sched.c, exit.c 有所了解。linux 0.11中进程状态有三种:就绪(运行)、等待、退出

  1. 新建进程时
    fork() -> sys_fork()-> kernel/system_call.s -> copy_process(),在 kernel/fork.c 文件中添加输出语句
int copy_process(int nr,……)
{
//    ……
// 设置 start_time 为 jiffiesp->start_time = jiffies;
//  新建进程,向log文件输出,'N'-新建fprintk(3, "%ld\t%c\t%ld\n", p->pid, 'N', jiffies); 
//       ……p->state = TASK_RUNNING;    
//  设置进程状态为就绪,向log文件输出,'J'-就绪fprintk(3, "%ld\t%c\t%ld\n", p->pid, 'J', jiffies); return last_pid;
}
  1. 进入睡眠态

修改 kenrel/sched.c 中的 sys_pause() 和 sleep_on() 和 interruptible_sleep_on()

int sys_pause(void)
{current->state = TASK_INTERRUPTIBLE;// 输出log文件if(current->pid != 0)fprintk(3, "%ld\t%c\t%ld\n", current->pid, 'W', jiffies);schedule();return 0;
}void sleep_on(struct task_struct **p)
{struct task_struct *tmp;
//    ……tmp = *p;
// 仔细阅读,实际上是将 current 插入“等待队列”头部,tmp 是原来的头部*p = current;  
// 切换到睡眠态current->state = TASK_UNINTERRUPTIBLE; // 输出log文件fprintk(3, "%ld\t%c\t%ld\n", current->pid, 'W', jiffies); schedule();  // 唤醒队列中的上一个(tmp)睡眠进程。if (tmp){tmp->state=0;//  输出log文件fprintk(3, "%ld\t%c\t%ld\n", tmp->pid, 'J', jiffies); }
}void interruptible_sleep_on(struct task_struct **p)
{struct task_struct *tmp;…tmp=*p;*p=current;
repeat:    current->state = TASK_INTERRUPTIBLE;//  输出log文件fprintk(3, "%ld\t%c\t%ld\n", current->pid, 'W', jiffies); schedule();if (*p && *p != current) { (**p).state=0;//  输出log文件fprintk(3, "%ld\t%c\t%ld\n", (*p)->pid, 'J', jiffies); goto repeat;}*p=NULL;if (tmp){tmp->state=0;//  输出log文件fprintk(3, "%ld\t%c\t%ld\n", tmp->pid, 'J', jiffies); }
}

修改 exit.c 中的 sys_waitpid()

int sys_waitpid(pid_t pid,unsigned long * stat_addr, int options)
{
//    ……if (flag) {if (options & WNOHANG)return 0;current->state=TASK_INTERRUPTIBLE;//  0号进程是守护进程,cpu空闲的时候一直在waiting,输出它的话是不会通过脚本检查的哦if(current->pid != 0)fprintk(3, "%ld\t%c\t%ld\n", current->pid, 'W', jiffies); schedule();
//    ……
}
  1. 调度算法

调度程序在分配CPU时会修改进程状态,同样需要记录,修改 kernel/sched.c 中的 schedule():

void schedule(void)
{
//    ……if (((*p)->signal & ~(_BLOCKABLE & (*p)->blocked)) &&(*p)->state==TASK_INTERRUPTIBLE) {(*p)->state=TASK_RUNNING;/*可中断睡眠 => 就绪*/fprintk(3,"%d\tJ\t%d\n",(*p)->pid,jiffies);}}//    ……// 如果当前进程和 next 进程不一样,则输出log文件if(current->pid != task[next] ->pid){// 当前进程由 运行 -> 就绪if(current->state == TASK_RUNNING)fprintk(3,"%d\tJ\t%d\n",current->pid,jiffies);// next进程由 就绪 -> 运行fprintk(3,"%d\tR\t%d\n",task[next]->pid,jiffies);}switch_to(next);
}
  1. 唤醒

修改 kernel/sched.c 中的 wake_ip():

void wake_up(struct task_struct **p)
{if (p && *p) {(**p).state=0;// 唤醒 最后进入等待序列的 进程fprintk(3,"%d\tJ\t%d\n",(*p)->pid,jiffies);*p=NULL;}
}
  1. 进程退出

进程结束了运行或在半途中终止了运行,那么内核就需要释放该进程所占用的系统资源,在 kernel/exit.c 文件中添加输出log文件指令:

int do_exit(long code)
{
//    ……current->state = TASK_ZOMBIE;// 退出一个进程,输出log文件fprintk(3, "%ld\t%c\t%ld\n", current->pid, 'E', jiffies); current->exit_code = code;tell_father(current->father);schedule();return (-1);	/* just to suppress warnings */
}

总结:实现log进程全面跟踪,Linux0.11包括六种状态转移,

  • 就绪 到 运行 :schedule()
  • 运行 到 就绪 :schedule()
  • 运行 到 睡眠 : sleep_on() 、interruptible_sleep_on()sys_pause() 、sys_waitpid()
  • 睡眠 到 就绪 :wake_up()
  • 新建
  • 退出

注意:系统无事可做的时候,进程 0 会不停地调用 sys_pause(),以激活调度算法。此时它的状态可以是等待态,等待有其它可运行的进程;也可以叫运行态,它是唯一一个在 CPU 上运行的进程,只不过运行的效果是等待。所以输出log文件时经常要判断当前进程pid是否为零,防止sys_pause() 不断输出log文件

编程输出log文件

cd ~/my_space/OS_HIT/oslab_Lab3/linux-0.11
make     // 编译
cd ..
./run// 在 Bochs 中查看 log 文件
more /var/process.log
sync   // 退出 bochs 时,刷新 cache,确保文件确实写入了磁盘。// 将 process.log 取出到 Ubuntu
sudo ./mount-hdc
cd hdc/var
mv process.log ../..
// 此时即可在Ubuntu中查看log文件了

三、统计时间与调度算法修改

使用 python 代码计算数据统计,计算平均周转时间、平均等待时间和吞吐率

sudo apt-get install python
chmod +x stat_log.py
./stat_log.py process.log 0 1 2 3 4 5 -g | more

按照实验任务书,接下来需要修改时间片大小再进行统计。具体修改 include/linux/sched.h 文件中的 INIT_TASK 宏定义第三个值,即修改15为期望的时间片大小,再运行 stat_log.py 分析

#define INIT_TASK \
/* state etc */    { 0,15,15, \
/* signals */    0,{{},},0, \

依次将时间偏设为1,5,10,15,20,25,50,100,150后,经统计分析log文件可以发现:
1)在一定的范围内,平均等待时间,平均完成时间的变化随着时间片的增大而减小。这是因为在时间片小的情况下,cpu将时间耗费在调度切换上,所以平均等待时间增加。
2)超过一定的范围之后,这些参数将不再有明显的变化,这是因为在这种情况下,RR轮转调度就变成了FCFS先来先服务了。随着时间片的修改,吞吐量始终没有明显的变化,这是因为在单位时间内,系统所能完成的进程数量是不会变的。


http://www.mrgr.cn/news/44166.html

相关文章:

  • Queue、Hashtable
  • 南昌网站建设让你的企业网站更具竞争力
  • 在CentOS7上安装mysql
  • 大数据分析的具体步骤
  • AtCoder Beginner Contest 374 (E + F)
  • VTC视频时序控制器,TPG图像测试数据发生器,LCD驱动——FPGA学习笔记19
  • 原码、反码、补码极简理解
  • 怎么避免在pod产生-派生炸弹(Fork Bomb)? k8s(kubernetes)
  • 漫谈前端:2025年框架是该选vue还是react?
  • Spring Boot 面向切面编程(AOP) 入门
  • 【C++驾轻就熟】vector深入了解及模拟实现
  • 【动态规划-最长公共子序列(LCS)】力扣1035. 不相交的线
  • LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
  • 本田汽车投资SiLC Technologies:携手共促自动驾驶技术新飞跃
  • 网站集群批量管理-Ansible-模块管理
  • 贪心算法相关知识
  • Linux下网络转发功能
  • Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
  • 老房翻新,弱配电箱需不需要加?
  • 【Rust练习】17.泛型