实验二:进程调度之先来先服务
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
typedef struct node
{
char name[10]; //进程标识符
int comet; //进程到来时间
char state; //进程状态
struct node *next;
}PCB;
PCB *ready, *finish, * run;
void insert(PCB *p);
void firstin();
void print();
/*创建初始进程PCB信息*/
void creatp()
{
char na[10];
int time;
PCB *p;
int n;
printf("请输入要创建的进程数");
scanf("%d",&n);
printf("输入进程号和到达的时间:\n");
int i=0;
for( i;i<n;i++)
{
p=(PCB *)malloc(sizeof(PCB));
scanf("%s",na);
scanf("%d",&time);
strcpy(p->name,na);
p->next=NULL;
p->comet=time;
p->state='w'; // w=wait 等待
insert(p); //将新产生的进程插入到就绪队列的合适位置
}
printf(" 先来先服务算法输出信息:\n");
printf("**********************************\n");
print();
if(run==NULL) firstin();
return;
}
/*进程就绪链表的插入算法,就绪链表按到来时间从小到大排列*/
void insert(PCB *p)
{
PCB *p1,*q;
p1=ready;
q=p1;
if(p1==NULL) //当插入的是第一个结点
{
p1=p;
ready=p1;
return;
}
else
{
while(p1!=NULL&&p1->comet<p->comet)
{
q=p1;
p1=p1->next;
}
if(q!=p1) //在链表中间或链尾插入结点
{
p->next=p1;
q->next=p;
}
else //在链表的表头插入结点
{
p->next=p1;
ready=p;
}
return;
}
}
/*将就绪队列的第一个进程投入运行*/
void firstin()
{
run=ready;
run->state='R';
ready=ready->next;
return;
}
/*先来先服务调度算法*/
void fcfsschedule()
{
while(run!=NULL)
{
print();
run->next=finish;
finish=run;
run->state='F';
run=NULL;
if(ready!=NULL) firstin();
}
}
/*进程PCB的输出*/
void print1()
{
printf("进程号 到达时间 状态\n");
}
void print2(PCB *p)
{
printf("%5s,%5d,%5c\n",p->name,p->comet,p->state);
}
void print()
{
PCB *q1;
q1=(PCB *)malloc(sizeof(PCB));
print1();
if(run!=NULL) print2(run);
q1=ready;
while(q1!=NULL)
{
print2(q1);
q1=q1->next;
}
q1=finish;
while(q1!=NULL)
{
print2(q1);
q1=q1->next;
}
//getchar();
}
/*主函数*/
void main()
{
ready=(PCB *)malloc(sizeof(PCB));
run=(PCB *)malloc(sizeof(PCB));
finish=(PCB *)malloc(sizeof(PCB));
ready=NULL;
run=NULL;
finish=NULL;
creatp();
fcfsschedule();
}