实验一进程创建与撤销

更新时间:2023-05-21 05:19:01 阅读量: 实用文档 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

#include<iostream>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#include<iomanip>
using namespace std;
typedef struct QNode
{
int data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct PCB
{
char NAME[20];
long ID;
float TIME;
int PRIORITY;

}PCB;
PCB pcb[100];
typedef struct LinkQueue
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
LinkQueue R;//消息缓冲队列
int N,m;//N为当前进程数,m用来存放用户是否返回主菜单的选择
void menu();
int InitQueue()//就绪队列初始化
{
R.front=R.rear=(QueuePtr)malloc(sizeof(QNode));
if(!R.front)
exit(-2);
R.front ->next =NULL;
return 1;
}
void returnMenu()
{
cout<<endl<<"是否回到主菜单(1.是,2.否)"<<endl<<"请选择:";
cin>>m;
if(m==1)
menu();
else if(m==2)
exit(0);
}
void create()//进程创建
{
//pcb[0].ID =0;
char name[20];
long id;
float time;
int priority;//定义这些变量用来接收用户输入的进程信息

QNode *p;//用来存放缓冲队列的指针
cout<<"请输入要创建进程的数目:";
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"进程ID:";
cin>>id;
for(int j=n-(i-1);j<n;j++)
{
while(id==pcb[j].ID)
{
cout<<"进程ID已存在"<<endl;
cout<<"进程ID:";
cin>>id;
}
}

cout<<"进程名:";
cin>>name;
cout<<"运行时间:";
cin>>time;
cout<<"优先级:";
cin>>priority;
N++;//保存当前就绪进程数
strcpy(pcb[N].NAME,name);
pcb[N].ID =id;
pcb[N].TIME =time;
pcb[N].PRIORITY =priority;

p=(QueuePtr)malloc(sizeof(QNode));//插入就绪队列
if(!p)
exit(-2);
p->data=N;
p->next=NULL;
R.rear->next=p;
R.rear=p;
}
for(int i=1;i<=N;i++)//按优先级排队
{
for(int j=i+1;j<=N;j++)
if(pcb[i].PRIORITY<pcb[j].PRIORITY)
{
pcb[0]=pcb[i];
pcb[i]=pcb[j];
pcb[j]=pcb[0];
}
}
returnMenu();


}
void kill()//进程终止
{
long id;
QNode *p;
cout<<"请输入要终止的进程ID:";
cin>>id;
p=R.front ;
if(p==NULL) cout<<"就绪进程为空!";
while(p->next!=NULL)//遍历就绪队列
{
if(id==pcb[p->next->data].ID)
{
p->next =p->next->next ;
if(p->next==NULL)//说明只有一个进程就绪
{
R.rear =p;//队列为空的条件
}
while(p->next!=NULL)
{
p->next ->data --;
pcb[p->next->data]=pcb[p->next->data+1];
p=p->next ;
}
if(R.front->next==NULL)
{
R.front =R.rear;//只有一个就绪进程,删除后变空队列
}
N--;
break;
}
p=p->next ;
}

returnMenu();
}
void display()
{
QNode *p;
p=R.front;
cout<<"ID"<<" "<<"名字"<<" "<<"运行时间"<<" "<<"优先级"<<endl;
while(p->next!=NULL)//遍历就绪队列
{
cout<<pcb[p->next->data].ID<<" "<<pcb[p->next->d
ata].NAME<<" "<<pcb[p->next->data].TIME <<" "<<pcb[p->next->data].PRIORITY<

<endl;
p=p->next ;
}
returnMenu();
}
void main()
{
InitQueue();
menu();
}
long c;
void menu()
{
system("cls");
QNode *p;//消息队列的结点指针
p=R.front;
cout<<""<<"进程创建与撤销"<<endl;
cout<<endl<<"1.进程创建"<<endl;
cout<<"2.进程撤销";
cout<<endl<<"3.就绪进程"<<endl;

int choice;
cout<<"请选择:&
quot;;
cin>>choice;
switch(choice)
{
case 1:create();break;
case 2:kill();break;
case 3:display();break;
default :exit(0);
}
}

本文来源:https://www.bwwdw.com/article/ci14.html

Top