#include <stdio.h>
#include <stdlib.h>
enum STATE { Ready = 1, Run, Block, Finish };
struct pcb {
int ID; // 进程名
int Priority; // 优先数
int Time; // 到达时间
int AllTime; // 进程还需要运行时间
int CPUTime; // 已用CPU时间
int StartBlock; // 进程的进入阻塞时间
int StartTime; // 进程的等待阻塞时间
char State; // 进程状态
struct pcb *Next; // 队列指针
} *ready = NULL, *p;
typedef struct pcb PCB;
void Sort(PCB *newPCB) {
PCB *first, *second;
int insert = 0;
if (ready == NULL || (newPCB->Priority > ready->Priority)) {
newPCB->Next = ready;
ready = newPCB;
} else {
first = ready;
second = first->Next;
while (second != NULL) {
if (newPCB->Priority > second->Priority) {
newPCB->Next = second;
first->Next = newPCB;
second = NULL;
insert = 1;
} else {
first = first->Next;
second = second->Next;
}
}
if (insert == 0) {
first->Next = newPCB;
}
}
}
void Input() {
int i, num;
printf("\n请输入进程数量: ");
scanf("%d", &num);
for (i = 0; i < num; i++) {
p = (struct PCB *)malloc(sizeof(PCB));
p->ID = i + 1;
printf("\n输入进程%d的信息:\n", p->ID);
printf("进程优先数: ");
scanf("%d", &p->Priority);
printf("进程需要运行时间: ");
scanf("%d", &p->AllTime);
p->Time = 3 * i;
p->CPUTime = 0;
p->StartBlock = 0;
p->StartTime = 0;
p->State = Ready;
p->Next = NULL;
printf("\n");
Sort(p);
}
}
int Length() {
int l = 0;
PCB *pr = ready;
while (pr != NULL) {
l++;
pr = pr->Next;
}
return l;
}
void OutPut(PCB *pr) {
printf("\nID\tState\tPriority\tAllTime\tCPUTime\n");
printf("%d\t%c\t%d\t%d\t%d\n", pr->ID, pr->State, pr->Priority, pr->AllTime, pr->CPUTime);
}
void Check() {
PCB *pr;
printf("\n****当前正在运行的进程是:\n");
OutPut(p);
pr = ready;
printf("\n****当前就绪队列状态为:\n");
while (pr != NULL) {
OutPut(pr);
pr = pr->Next;
}
}
void Destroy() {
printf("\n进程 [%d] 已完成.\n", p->ID);
free(p);
}
void Running() {
p->CPUTime++;
p->State = Run;
if (p->CPUTime == p->AllTime) {
Destroy();
} else {
(p->Priority)--;
p->State = Ready;
Sort(p);
}
}
int main() {
int h = 0;
char ch;
Input();
while ((Length() != 0) && (ready != NULL)) {
ch = getchar();
h++;
printf("\n执行进程号:%d \n", h);
p = ready;
ready = p->Next;
p->Next = NULL;
p->State = Ready;
Check();
Running();
printf("\n按任一键继续......");
ch = getchar();
}
printf("\n\n进程已经完成.\n");
ch = getchar();
return 0;
}