进程管理
题目描述
在操作系统中,进程管理是非常重要的工作,每个进程都有唯一的进程标识(PID)。每个进程都可以启动子进程,此时我们称它为其子进程的父进程,除了 PID 为 0 的进程之外,每个进程有且只有一个父进程,在这个任务中,你需要实时维护操作系统运行中的三个基本操作:
1.FORK PID1 PID2:标识为 PID1 的进程启动了一个标识为 PID2 的子进程。
2.KILL PID:结束标识为 PID 的进程。请注意,与此同时所有 PID 的子进程也将同时结束。
如果 PID 是不存在或已经结束的进程,则不做任何操作。
3.QUERY PID:查询标识为 PID 的进程是否仍然存在。
在初始状态下,系统只开启了 PID 为 0 的进程,并且在任何情况下该进程不会结束。
输入格式
输入的第一行是一个整数 T(T<=50),表示输入的数据组数。
每组测试数据的第一行是一个整数 N(1<=N<=100),表示操作的数量。
没下来 N 行,每行按照上面的描述给出每个操作,输入保证所有的进程的 PID 都不相同,
且一个进程结束后不会被重新启动,所有 PID 都是[1,100]之间的整数。
输出格式
QUERY PID:存在输出 Yes ,不存在输出 NO
输入样例
2
5
FORK 0 1
QUERY 1
KILL 1
QUERY 1
QUERY 2
1
QUERY 0
输出样例
Yes
No
No
Yes
代码1
#include<iostream>
#include<string.h>
#include<string>
#include<vector>
using namespace std;
//进程管理
bool mark[105];//标记进程是否存在
vector<vector<int> >p(105);
void del(int x) {
if(mark[x]!=false) {
mark[x]=false;
for(int i=0; i<p[x].size(); i++) {
del(p[x][i]);
}
}
}
int main() {
int T,N,x,y;
string s;
cin>>T;
while(T--) {
memset(mark,0,sizeof(mark));
for(int i=0; i<p.size(); i++) {
p[i].clear();
}
cin>>N;
mark[0]=true; // PID=0的进程不会结束
for(int i=0; i<N; i++) {
cin>>s>>x;
if(s=="FORK") {
cin>>y;
p[x].push_back(y);
mark[y]=true;
} else if(s=="QUERY") {
if(mark[x]==true) {
cout<<"Yes"<<endl;
} else {
cout<<"No"<<endl;
}
} else if(s=="KILL") { //递归删除进程
del(x);
}
}
}
return 0;
}
代码2
#include<iostream>
#include<string.h>
#include<string>
#include<vector>
using namespace std;
//进程管理
struct node{
vector<int >sonlist;
bool turnOn;
};
node tree[105];
void create(int index){
tree[index].sonlist.clear();
tree[index].turnOn=true;
}
void del(int index){
if(tree[index].turnOn!=false){
for(int i=0;i<tree[index].sonlist.size();i++){
del(tree[index].sonlist[i]);
}
tree[index].sonlist.clear();
tree[index].turnOn=false;
}
}
int main() {
int T,N,father,son,index;
string op;
cin>>T;
while(T--) {
for(int i=0;i<105;i++){ //初始化
tree[i].sonlist.clear();
tree[i].turnOn=false;
}
//初始化 PID=0 的进程
tree[0].turnOn=true;
cin>>N;
for(int i=0; i<N; i++) {
cin>>op;
if(op=="FORK") {
cin>>father>>son;
create(son);
tree[father].sonlist.push_back(son);
} else if(op=="QUERY") {
cin>>index;;
if(tree[index].turnOn==true) {
cout<<"Yes"<<endl;
} else {
cout<<"No"<<endl;
}
} else if(op=="KILL") {
cin>>index;
del(index);
}
}
}
return 0;
}