链表模拟简单的进程调度
程序代码:/*
*模拟简单的进程调度
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct PCB
{
char name[10];
int rtime;
int priorityNum;
char state;
struct PCB *next;
}PCB;
/*
*初始化PCB
*/
PCB *initPCB()
{
PCB *head;
head=(PCB *)malloc(sizeof(PCB));
if(NULL==head)
{
exit(-1);
}
head->next=NULL;
return head;
}
/*
* 新建一个节点,并返回
*/
PCB *inputValue()
{
PCB *temp = NULL;
temp = initPCB();
printf("please input the information of process\n");
printf("name:");
scanf("%s",temp->name);
printf("run time:");
scanf("%d",&temp->rtime);
printf("priorityNum:");
scanf("%d",&temp->priorityNum);
temp->state = 'R';
printf("\n");
return temp;
}
/*
*找到优先级最高的进程
*/
void findProcess( PCB * head, PCB * pCurrent )
{
if( head->next == NULL )
{
head->next = pCurrent;
return ;
}
/* 从大到小排 */
PCB* p = head->next;
PCB* q = head;
while( p != NULL )
{
if( (pCurrent->priorityNum) > (p->priorityNum) )
{
q->next = pCurrent;
pCurrent->next = p;
break;
}
q = p;
p = p->next;
}
q->next = pCurrent;
}
/*
*打印PCB
*/
void printPCB( PCB * head )
{
PCB *temp;
temp = head->next;
while( temp!=NULL )
{
printf("\n process name: %s\n run time: %d\n priority num: %d\n process state:%c\n",
temp->name,temp->rtime,temp->priorityNum,temp->state);
temp = temp->next;
}
printf("\n\n");
}
/*
*运行进程
*/
void runProcess( PCB * head,PCB * selected )//选中一进程 优先数减一 运行时间减一 如果运行的时间为0 就将装太改为E 如果不为0 加入队列 重新比较 获得优先数最大进程 依次下去直到
{ //所有的进程状态都为E 求实现??????????????????????
PCB *p,*q;
while( selected->next != NULL )
{
selected->priorityNum--;
selected->rtime--;
if( selected->rtime == 0 )
{
selected->state = 'E';
break;
}
/*将运行时间不为0的进程加入队列*/
p = head->next;
q = head;
if( q == NULL )//空队列
{
q = selected;
}
if( (selected->priorityNum) > (p->priorityNum) )
{
q->next = selected;
selected->next = p;
}
}
}
int main()
{
PCB *head = NULL;
PCB *temp = NULL;
head = initPCB(); // 头结点为空
for(int i=0;i<3;i++)
{
temp = inputValue();
findProcess(head,temp);
printf("=================\n");
}
runProcess(head,temp);
printPCB(head);
return 0;
}






