⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 czxt.c

📁 操作系统课程设计 操作系统课程设计 操作系统课程设计 操作系统课程设计
💻 C
字号:
#include"stdio.h"
#include"stdlib.h"
#include "string.h"
#define WAIT 1
#define RUN 2
#define FINISH 3

typedef struct pcb
{
int num;
struct pcb *next;
int priority;
int timeneed;
int state;
}pcb;/*用此结构体来模拟一个进程*/

struct pcb *head;
struct pcb *run;

pcb *jccreat(int n)/*此函数用于创建进程队列*/
{
int i=1;
pcb *head,*p,*q;

randomize();/*随机函数的初始化*/

head=(pcb *)malloc(sizeof(pcb));/*创建一个空表头*/
p=head;

for(i=1;i<=n;i++)/*用循环来创建指定个结点*/
{
q=(pcb *)malloc(sizeof(pcb));
p->next=q;
q->num=i;
q->next=NULL;
q->priority=random(10);/*随机产生优先级*/
q->timeneed=random(10);/*随机产生运行时间*/
q->state=WAIT;
p=q;
}

return head;/*返回表头指针*/
}

pcb *getmaxpriority(struct pcb *head)/*此函数用来挑选一个优先级最大的进程来执行*/
{
struct pcb *p,*q;
int max;
p=head->next;
max=p->priority;/*初始max为队首结点的优先级*/
q=p;
while(p)
{
if(p->priority>max)/*逐一比较,选出优先级最大的结点*/
{max=p->priority;
q=p;}
p=p->next;
}
return q;
}

void delect(struct pcb *head,struct pcb *run)/*此函数用来将运行完的进程删除出进程队列*/
{
struct pcb *q=head;

while(q->next)/*扫描进程队列,找到执行完了的进程*/
{
if(q->next->num==run->num)/*判断是不是已完成的进程*/
{
if(run->next!=NULL)
q->next=run->next;
else q->next=NULL;
free(run);/*释放申请的空间*/
return;
}
q=q->next;
}

}

void control()/*此函数是用来控制各个进程的执行和调度*/
{
struct pcb *p;
run=head->next;/*初始让第一个进程运行*/
run->state=RUN;
while(run)
{
if(run->timeneed>0)/*如果当前run指针指向的进程所需时间不为零,状态为运行状态,就让这个进程运行*/
if(run->state==RUN)
{printf("pcb%d is running.\n",run->num);
printf("Waiting list:");/*显示整个等待队列*/
p=head->next;
while(p)
{
if(p!=run)
printf("pcb%d ",p->num);
p=p->next;
}
printf("\n");
delay(10000000);/*模拟进程运行*/
run->timeneed--;/*进程需要时间减一*/
run->priority=run->priority-3;/*进程优先级减三*/
}

if(run->timeneed!=0)
{
if(run->priority<=head->next->priority)/*如果当前运行完的进程的优先级低于队首进程的优先级*/
{run->state=WAIT;
run=getmaxpriority(head);/*则从进程队列中挑选一个优先级最大的进程来运行*/
run->state=RUN;}
}
else
{ printf("pcb%d is finished.\n",run->num);
delay(10000000);
delect(head,run);/*删除该结点*/
if(head->next!=NULL)/*判断进程队列是不是为空*/
{run=head->next;
run->state=RUN;}
else
{printf("All progresses are done.\n");

return;}
}
}
}

main()
{
int n;
int flag=1;

printf("Enter the number of the progresses:");
scanf("%d",&n);/*输入要创建的进程的数量*/

head=jccreat(n);/*创建进程队列,将链表的表头赋给head指针*/
run=head->next;/*run指针指向正在运行的进程的pcb*/
while(run)
{
printf("num: %d ,priority: %d ,timenees: %d \n",run->num,run->priority,run->timeneed);

run=run->next;
} /*将刚创建的进程队列打印出来*/
while(flag)/*由flag的值判断是否继续执行control()函数*/
{
if(head->next)/*判断进程是否完成*/
control();
else flag=0;
}
getch();
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -