#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define null 0
typedef struct PCB{
char name[12];
int priority;
int time ;
char state[6];
struct PCB *next;}PCB;
PCB *create(int n);
void run(PCB *head);
main(){
PCB *head1,*p1 ;
int N;
printf(" *********该程序模拟进程按高优先权优先的调度*********");
printf("\n");
printf(" *********若输入运行时间为0则将其状态改为结束*********");
printf("\n输入所含的进程的个数:");
scanf("%d",&N);
head1=create(N);
p1=head1->next;
clrscr();
printf(" \t\t进程名 \t优先数 \t运行时间");
while(p1->next!=null){
printf("\n\t\t %s \t %d \t %d",p1->name,p1->priority,p1->time);
p1=p1->next;}
printf("\n\t\t %s \t %d \t %d",p1->name,p1->priority,p1->time);
printf("\n开始模拟按高优先权优先的进程调度,\n");
printf("\n在优先权相同的情况下运行时间短的先执行:\n");
run(head1);
printf("进程调度完成!");
}
PCB *create(int n){
int i,N;
PCB *head ;
PCB *p1,*p2;
N=n;
head=(PCB*)malloc(sizeof(PCB));
head->next=null;
p1=head;
printf("\n要求运行时间小于优先数且优先数按非递增顺序输入\n");
printf("\n\n");
for(i=0;i<N;i++)
{p2=(PCB*)malloc(sizeof(PCB));
printf("依次输入该进程的名称(char)优先数(int)所需运行时间(int),之间以Enter做间隔:\n");
scanf("%s%d%d",&p2->name,&p2->priority,&p2->time);
strcpy(p2->state,"R");
p2->next=null;
p1->next=p2;
p1=p2;
}
return head;
}
void run(PCB *head) {
PCB *h,*p1,*p2,*p3,*p4;
int i,j,k,l,t=0;
/*t用于标志运行时间为0的进程是否为序列的第一个,
t=0表示是第一个,t!=0表示不是第一个*/
k=1;
l=0;
h=head;
p1=p2=h->next;
p3=p1->next;
/*该部分判断是否有运行时间为0的进程,从而调整进程顺序*/
while(p3->next!=null )
{if(p1->time==0&&t==0)
{strcmp(p1->state,"E");free(p1);h->next=p3;p1=p3;p2=p3=p3->next; }
else{p1=p2=p3;p3=p3->next;t++; }
if(t!=0)break;}
if(p1->time==0&&(t==0)) /*第一个运行时间为0,判断下一个*/
{strcmp(p1->state,"E");free(p1);h->next=p2;p2->next=null;} /* 运行时间为0则修改状态为结束“E”*/
if(t!=0){
p1=h->next;
p2=p1->next;
while(p2->next!=null )
{if(p2->time==0){p3=p2->next;p1->next=p3;free(p2);p2=p3; }
else{p1=p2;p2=p2->next;}
}
}
if(p2->time==0){free(p2);p1->next=null;}
p1=h->next;
p3=p2=p1->next;
/*该部分开始执行进程调度*/
do{
L1:i=(p1->priority-p2->priority);
if(i==0)i++;
for(j=0;j<i;j++){
printf("---\t%s被调用",p1->name);
p1->time--;
l++;
printf("\t-");
if((l%3==0)||(k%3==0)){printf("\n");l=0; } /*调整格式*/
if(p1->time==0){
strcpy(p1->state,"E");
printf("\n");
printf("\t\t ***-*-*-第%d个完成调度的进程为: %s",k++,p1->name);
l=0;
printf("\n");
}
if((strcmp(p1->state,"E"))==0&&j!=i-1)break;
}
p1->priority=p1->priority-i;
if(strcmp(p1->state,"E")==0) { p1=p2;
h->next=p1;
if(p1->next==null ) break;
p3=p2=p1->next;
goto L1;}
/*根据优先数与运行时间判断先执行的进程*/
if((p1->priority<p2->priority )||((p1->priority==p2->priority) && (p1->time)>(p2->time)))
if(p2->next!=null){
{p3=p2->next;
h->next=p2;
if( p1->priority>p3->priority||p1->priority==p3->priority)
{p2->next=p1;
p1->next=p3;}
else {p4=p3->next;
p3->next=p1;
p1->next=p4;}
p1=h->next;
p3=p2=p1->next;
} }
else{h->next=p2;p2->next=p1;p1->next=null;
p1=h->next;
p3=p2=p1->next;}
}while(p1->next!=null);
k=1;
for(i=p1->time;i>0;i--)
{printf("---\t%s被调用",p1->name,k++);
if(k%3==0)printf("\n");}
printf("\t\t ***-*-*-第%d个完成调度的进程为: %s\n",k,p1->name);
}