进程运行轨迹的跟踪与统计
进程从创建(Linux 下调用 fork())到结束的整个过程就是进程的生命期,进程在其生命期中的运行轨迹实际上就表现为进程状态的多次切换,如进程创建以后会成为就绪态;当该进程被调度以后会切换到运行态;在运行的过程中如果启动了一个文件读写操作,操作系统会将该进程切换到阻塞态(等待态)从而让出 CPU;当文件读写完毕以后,操作系统会在将其切换成就绪态,等待进程调度算法来调度该进程执行……
process.c解读
void cpuio_bound(int last, int cpu_time, int io_time)
{
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(¤t_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 );
last -= cpu_time;
if (last <= 0 )
break;
/* IO Burst */
/* 用sleep(1)模拟1秒钟的I/O操作 */
sleep_time=0;
while (sleep_time < io_time)
{
sleep(1);
sleep_time++;
}
last -= sleep_time;
}
}
使用last来判断退出,当last时间为小于0表示时间到达了。
记录一个开始时间,
消耗时间来假设使用了一个cpu时间,减去一个cpu时间,表示调用
使用sleep函数来模拟一秒,直到大于等于一个io时间退出,减去一个io时间,表示调用
调用完仍然last仍然没有小于0,继续调用。
proccess.c修改:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
#define HZ 100
void cpuio_bound(int last, int cpu_time, int io_time);
int main(int argc, char * argv[])
{
pid_t p1,p2,p3,p4;
p1=fork();
if(p1<0){
printf("file to fork");
}else if(p1==0){
printf("ppid:%4d pid:%4d\n",getppid(),getpid());
cpuio_bound(10,1,0);
}else{
printf("ppid:%4d pid:%4d fpid:%4d\n",getppid(),getpid(),p1);
}
p2=fork();
if(p2<0){
printf("file to fork");
}else if(p2==0){
printf("ppid:%4d pid:%4d\n",getppid(),getpid());
cpuio_bound(10,0,1);
}else{
printf("ppid:%4d pid:%4d fpid:%4d\n",getppid(),getpid(),p2);
}
p3=fork();
if(p3<0){
printf("file to fork");
}else if(p3==0){
printf("ppid:%4d pid:%4d\n",getppid(),getpid());
cpuio_bound(10,1,1);
}else{
printf("ppid:%4d pid:%4d fpid:%4d\n",getppid(),getpid(),p3);
}
p4=fork();
if(p4
6547



被折叠的 条评论
为什么被折叠?



