实验二:先来先服务进程调度
#include <stdio.h>
#include <malloc.h>
typedef struct jinchen //定义结构体
{
char name[5];
int tijiaoshijian;
int reachtime;
int runtime;
int beirun;
int accomplishtime;
char state;
int flag;
struct jinchen *next;
}PCB;
PCB *finish,*ready;//定义队列 一个完成一个就绪
int time=0;
int t=0;
int num;
void InitPcb() //进程初始化
{
int i,j=0;
PCB *p,*q,*l,*m,*k,*n;
printf("请输入进程个数:");
scanf("%d",&num);
ready=(PCB *)malloc(sizeof(PCB));
ready->next=NULL;
finish=(PCB *)malloc(sizeof(PCB));
finish->next=NULL;
l=(PCB *)malloc(sizeof(PCB));
l->next=NULL;
p=l;
for(i=0;i<num;i++)
{
q=(PCB *)malloc(sizeof(PCB));
printf("\n进程号 %d:\n",i);
printf("请输入进程名:");
scanf("%s",q->name);
q->reachtime=0;
printf("请输入提交时间:");
scanf("%d",&(q->tijiaoshijian));
printf("请输入运行时间:");
scanf("%d",&(q->runtime));
q->beirun=q->runtime;
q->state='R';
q->flag=0;
if(i!=0) //链接就绪进程
{
//q->next=NULL;
q->next=p->next;
p->next=q;
p=p->next;
}
else //第一个进程插入就绪队列
{
p->next=q;
p=p->next;
p->next=NULL;
}
}
p=l->next;
k=ready;
for(i=0;i<num;i++) //按照提交时间排序
{
q=l->next;
t=1000;
while(q!=NULL)
{
if(q->tijiaoshijian<t&&q->flag==0)
{
t=q->tijiaoshijian;
m=(PCB *)malloc(sizeof(PCB));
m->next=NULL;
m->accomplishtime=q->accomplishtime;
m->beirun=q->beirun;
m->flag=q->flag;
for(j=0;j<5;j++)
m->name[j]=q->name[j];
m->reachtime=q->reachtime;
m->runtime=q->runtime;
m->state=q->state;
m->tijiaoshijian=q->tijiaoshijian;
n=q;
}
q=q->next;
}
p=p->next;
n->flag=1;
m->flag=1;
k->next=m;
k=k->next;
}
k->next=NULL;
}
void display() //函数作用:计算和显示相关输出
{
PCB *p;
int m,n=0,k=0,l;
p=finish->next;
while(p!=NULL)
{
printf("进程名 :%s",p->name);
m=p->accomplishtime-p->tijiaoshijian;
printf("周转时间:%d",m);
l=m/(p->beirun);
printf("带权周转时间:%d",l);
printf("\n");
n=m+n;
k=l+k;
p=p->next;
}
printf("平均周转时间:%d\n",n/num);
printf("平均带权周转时间:%d\n",k/num);
}
void Use()//进程调用
{
int j;
PCB *p=ready->next,*k=ready,*q,*n=finish;
while(k->next!=NULL)
{
p=ready->next;
for(j=0;j<num&&p!=NULL;j++)
{
time++;
//printf("%d\n\n",++t);
if(p->reachtime==0)
p->reachtime=time;
if(p->state!='C')
{
printf("正在运行:%s\n",p->name);
p->runtime--;
if(p->runtime!=0) //进程没有运行完,放入队列最后
{
q=p;
while(q->next!=NULL)
q=q->next;
ready->next=p->next;
q->next=p;
p=ready->next;
q=q->next;
q->next=NULL;
}
else //进程运行完,放入完成队列
{
p->state='C';
printf("%s进程完成\n",p->name);
p->accomplishtime=time;
n->next=p;
n=p;
ready->next=p->next;
p->next=NULL;
}
}
}
}
}
int main()
{
PCB *p;
InitPcb();
Use();
display();
p=finish->next;
printf("运行完毕!*说明:已运行完成的进程放入完成队列,未运行完成的进程放在队列最后");
}