操作系统用C语言模拟进程基于优先级的调度程序

2019-07-14 11:21发布

系统中有若干个进程,每个进程由进程控制块(PCB)来标识。进程控制块的内容有:进程名、链接指针、到达时间、运行时间、完成时间、进程优先数和进程状态等。进程优先数为整数型,优先数小优先级高。 #include #include typedef struct pcb { char name[5]; //进程名 int priority; //优先级 ,数值越小,优先级越高 int arrivetime; //到达时间 int runtime; //运行时间 int finishtime;//完成时间 int time; char state; //进程状态 "C" 代表完成,"R"代表就绪 struct pcb* link; }PCB; PCB *ready = NULL, *p; void disp(PCB* p); PCB * sort(PCB * p) { PCB *first, *second; int insert = 0; if (ready == NULL || (p->priority) < (ready->priority)) { p->link = ready; ready = p; } else if( p->priority==ready->priority) //如果优先级相同,则按时间排序 { if(p->arrivetimearrivetime) { p->link=ready; ready=p; } else { p->link=ready->link; ready->link=p; } } else if(p->priority>ready->priority) { first = ready; second = first->link; while (second != NULL) { if (p->priority < second->priority) { p->link = second; first->link = p; insert = 1; break; } else if(p->priority==second->priority) { if(p->arrivetimearrivetime) { p->link = second; first->link = p; insert = 1; break; } else { p->link=second->link; second->link=p; insert=1; break; } } else if(p->priority>second->priority) { first = first->link; second = second->link; } } if (insert == 0) { first->link = p; p->link = NULL; } } return ready; } void input() { int i,j; printf(" 请输入进程个数:"); scanf("%d",&j); for(i=1;i<=j;i++) { printf(" 第%d个进程 ",i); p=(PCB*)malloc(sizeof(PCB)); printf(" 输入进程名:"); scanf("%s",p->name); printf(" 输入进程需运行的时间:"); scanf("%d",&(p->runtime)); printf(" 输入进程优先数:"); scanf("%d",&(p->priority)); printf(" 输入进程的到达时间:"); scanf("%d",&(p->arrivetime)); p->state='R'; p->link=NULL; sort(p); } printf("按进程的优先级进行排序! "); p=ready; while (p != NULL) { disp(p); p = p->link; } } int maxnumber(PCB *p) { int max; max=p->arrivetime; while(p->link!=NULL) { if(maxlink->arrivetime) { max=p->link->arrivetime; } p=p->link; } return(max); } void disp(PCB* p) { printf("进程名 优先级 到达时间 运行时间 状态 "); printf("%s ",p->name); printf("%d ",p->priority); printf("%d ",p->arrivetime); printf("%d ",p->runtime); printf("%c ",p->state); } void run(PCB *p) { PCB *s,*q; int time=0,a,sum=0,n=0; float sum1=0.0; printf("进程的调度开始! "); p=ready; s=p; a=maxnumber(p); while(p!=NULL) { if(p->state=='C') { break; } while(s!=NULL) { n=n+1; s->time=s->runtime; s=s->link; } printf("进程%s运行一次 ",p->name); p->runtime--; p->priority++; time=time+1; p->finishtime=time+a; if(p->runtime==0) { p->state='C'; printf("进程名为%s,其周转时间为 %d ",p->name,(p->finishtime)-p->arrivetime); sum+=(p->finishtime)-(p->arrivetime); printf("进程名为%s的带权周转时间%f ",p->name,((p->finishtime)-(p->arrivetime))*1.0/(p->time)); sum1+=(time*1.0)/((p->finishtime)-(p->arrivetime)); ready=p->link; p->link=NULL; p=ready; } else { ready=p->link; p->link=NULL; p=sort(p); } } printf("平均周转时间为%f ",sum*1.0/n); printf("平均带权周转时间%f ",sum1*1.0/n); } void main() { input(); p=ready; run(p); }