实验二 用C语言表示进程的调度

实验二

一、 实验目的

通过模拟进程的调度,进一步了解进程的调度的具体过程。

二、 实验内容和要求

1.进程PCB的结构体定义

2.定义队列

3.输入进程序列

4.排序(按到位时间)

5.输出进程运行的结果

三、程序

#include<stdio.h>
#include<malloc.h>
#include<time.h>

/*定义一个Course类型的结构体*/
typedef struct queue{
int number;
int intime;
int runningtime;
int alltime;
int waitingtime;
struct node *next;
}Course;
/*定义一个PCB类型来表示队列*/
typedef struct node2{
Course *front;
Course *rear;
}PCB;
/*初始化队列*/
PCB initqueue(){
PCB q;
q.front=(Course *)malloc(sizeof(Course));
q.front->next=NULL;
q.rear=q.front;
return(q);
}
/*进入队列*/
PCB inserq(PCB q,int x,int j,int y,int k){
Course *p;
p=(Course *)malloc(sizeof(Course)); //申请结点p
p->number=x;//x.j.y.k储存到新结点p中
p->intime=j;
p->runningtime=y;
p->waitingtime=k;
p->alltime=y+k;
p->next=NULL;//p的指针域置空
q.rear->next=p;//指针域指向p,p成为新的队尾
q.rear=p; //对尾指针域指向p,保证rear指向新的队尾
return (q);
}
/* 打印进程调度的结果*/
void display(PCB q)
{
Course *p;
printf("\n队列:\n");
p=q.front->next;
while(p!=NULL)
{
printf("进入的顺序:%d ",p->intime);printf("\n");
printf("进程的编号:%d ",p->number);
printf("运行的时间:%d ",p->runningtime);
printf("等待的时间:%d ",p->waitingtime);
printf("所用的总时间:%d ",p->alltime);
printf("\n");
p=p->next;
}
}

main(){
int x,y,z,i=0,k,j=1/*用来记录进程进入的顺序*/;
PCB q;
q=initqueue();
for(i=0;i<5;i++ ){
printf("请输入进程的编号:");
scanf("%d",&x);
printf("请输入进程的运行的时间:");
scanf("%d",&y);
k=rand()%10;//随机产生0-9的数,代表进程要等待的时间。
q=inserq(q,x,j,y,k);
j++;
}
display(q);

}
 

initqueue()//初始化队列
1
inserq()//进入队列
1
display()//打印队列
3. 主要程序段及其解释:

/*主函数,实现对结构体类型变量的定义以及对队列的使用*/<br>main(){
int x,y,z,i=0,k,j=1/*用来记录进程进入的顺序*/;
PCB q;
q=initqueue();
for(i=0;i<5;i++ ){
printf("请输入进程的编号:");
scanf("%d",&x);
printf("请输入进程的运行的时间:");
scanf("%d",&y);
k=rand()%10;//随机产生0-9的数,代表进程要等待的时间。
q=inserq(q,x,j,y,k);
j++;
}
display(q);<br>}

/*定义一个Course类型的结构体*/
typedef struct queue{
int number;
int intime;
int runningtime;
int alltime;
int waitingtime;
struct node *next;
}Course;

/*初始化队列*/
PCB initqueue(){
PCB q;
q.front=(Course *)malloc(sizeof(Course));
q.front->next=NULL;
q.rear=q.front;
return(q);
}
/*进入队列*/
PCB inserq(PCB q,int x,int j,int y,int k){
Course *p;
p=(Course *)malloc(sizeof(Course)); //申请结点p
p->number=x;//x.j.y.k储存到新结点p中
p->intime=j;
p->runningtime=y;
p->waitingtime=k;
p->alltime=y+k;
p->next=NULL;//p的指针域置空
q.rear->next=p;//指针域指向p,p成为新的队尾
q.rear=p; //对尾指针域指向p,保证rear指向新的队尾
return (q);
}

/* 打印进程调度的结果*/
void display(PCB q)
{
Course *p;
printf("\n队列:\n");
p=q.front->next;
while(p!=NULL)
{
printf("进入的顺序:%d ",p->intime);printf("\n");
printf("进程的编号:%d ",p->number);
printf("运行的时间:%d ",p->runningtime);
printf("等待的时间:%d ",p->waitingtime);
printf("所用的总时间:%d ",p->alltime);
printf("\n");
p=p->next;
}
}

四、总结

使用C语言来对进程的调度,是一件比较有难度的事情,有很多不懂得地方。

posted @ 2016-04-06 22:53  26黄培康  阅读(1011)  评论(0编辑  收藏  举报