#include<stdio.h> #include<string.h> #define MAX 10 typedef struct process { char name[10]; int priority; int ReachTime; int NeedTime; int UsedTime; char state; }PCB; int n=0; int pTime; PCB static pcbs[MAX]; void sort(){ int i,j; PCB pcb; for(i=0;i<n;i++){ for(j=n-2;j>=i;j--){ if(pcbs[j+1].ReachTime < pcbs[j].ReachTime) { pcb = pcbs[j]; pcbs[j] = pcbs[j+1]; pcbs[j+1] = pcb; } } } for(i=0;i<n;i++){ for(j=n-2;j>=i;j--){ if(pcbs[j+1].priority > pcbs[j].priority) { pcb = pcbs[j]; pcbs[j] = pcbs[j+1]; pcbs[j+1] = pcb; } } } if(pcbs[0].state!='F') { pcbs[0].state='R'; } } void print(){ int i; sort(); printf(" 进程名 | 优先级 |到达时间|需要时间|已用时间|进程状态 "); for(i=0;i<n;i++){ printf("%8s%8d%8d%8d%8d%8c ",pcbs[i].name,pcbs[i].priority,pcbs[i].ReachTime,pcbs[i].NeedTime,pcbs[i].UsedTime,pcbs[i].state); } } void AddProcess(){ PCB i; char ch; while(1){ printf(" 请输入进程名:"); scanf("%s",&(i.name)); printf("请输入进程优先级:"); scanf("%d",&(i.priority)); printf("请输入需要运行时间:"); scanf("%d",&(i.NeedTime)); i.ReachTime = n; i.UsedTime = 0; i.state = 'W'; pcbs[n] = i; n++; printf("你是否还要继续添加?"); do { scanf("%c",&ch); }while(ch==' ' || ch==' '); if(ch != 'y') break; } printf(" 添加进程完毕 "); } void attemper(){ do { if( pcbs[0].NeedTime - pcbs[0].UsedTime > pTime) { pcbs[0].UsedTime += pTime; pcbs[0].priority--; pcbs[0].state = 'W'; } else { pcbs[0].UsedTime = pcbs[0].NeedTime; pcbs[0].priority = -1; pcbs[0].state = 'F'; } print(); }while(pcbs[0].state!='F'); } void face(){ char ch; do{ printf(" 增加进程并调度,请按1"); printf(" 打印进程,请按2"); printf(" 任务结束,请按0"); printf(" 请选择:"); do{ scanf("%c",&ch); }while(ch == ' ' || ch ==' '); switch(ch){ case '1': AddProcess(); print(); attemper(); break; case '2': print(); break; case '0':break; } }while(ch!='0'); } int main(){ printf(" 请设置时间片大小:"); scanf("%d",&pTime); face(); return 0; }