操作系统模拟实验(进程的撤销与创建)
原文链接 http://woodrat.xyz/2014/12/08/%e6%93%8d%e4%bd%9c%e7%b3%bb%e7%bb%9f%e6%a8%a1%e6%8b%9f%e5%ae%9e%e9%aa%8c%e8%bf%9b%e7%a8%8b%e7%9a%84%e6%92%a4%e9%94%80%e4%b8%8e%e5%88%9b%e5%bb%ba/
注:以下为加速网络访问所做的原文缓存,经过重新格式化,可能存在格式方面的问题,或偶有遗漏信息,请以原文为准。
一个很简陋的Python实现 : )
# -- coding: utf-8 -- class Pcb(object): def init(self): self.pid = None self.ppid = None # id of parent self.arrive_time = 0 self.need_time = 0 self.pprio = 0 #priority
def set_pid(self, pid):
self.pid = pid
def set_parent(self, parent):
self.ppid = parent
def set_arrive_time(self, arrive_time):
self.arrive_time = arrive_time
def set_need_time(self, need_time):
self.need_time = need_time
class Pnode(object): def init(self): self.node = Pcb() self.child = []
def set_node_pid(self, pid):
self.node.set_pid(pid)
def set_node_parent(self, ppid):
self.node.set_parent(ppid)
def set_node_arrtime(self, arrtime):
self.node.set_arrive_time(arrtime)
def set_node_needtime(self, needtime):
self.node.set_need_time(needtime)
def get_node_pid(self):
return self.node.pid
def get_node_parent(self):
return self.node.ppid
def get_node_arrtime(self):
return self.node.arrive_time
def get_node_needtime(self):
return self.node.need_time
class Pnodes(object): def init(self): self.root = Pnode() self.root.set_node_pid(0) self.nodes = {self.root.get_node_pid():self.root}
def createpc(self,pid,ppid):
if len(self.nodes) == 0:
return 0
p = self.nodes
if pid in p:
print "process already exists"
elif not ppid in p:
print "parent process does not exist"
else:
p[pid] = Pnode()
p[pid].set_node_pid(pid)
p[pid].set_node_parent(ppid)
p[ppid].child.append(pid)
def deletepc(self, pid):
if pid == 0:
print "pid 0 can't be deleted"
return 0
if not(pid in self.nodes):
print "process not exists"
return 0
if len(self.nodes[pid].child) == 0:
ppid = self.nodes[pid].get_node_parent()
self.nodes[ppid].child.remove(pid)
self.nodes.pop(pid)
else:
for cpid in self.nodes[pid].child:
self.deletepc(cpid)
self.deletepc(pid)
def show(self):
for pcb in self.nodes:
print pcb," : ", self.nodes[pcb].child
def main(): pnodes = Pnodes() while(1): cmd = raw_input("cmd:") if cmd == "exit": break if cmd == "show": pnodes.show() else: if "createpc" in cmd: cmd = cmd[9:-1] pcno,ppcno = map(int, cmd.split(",")) pnodes.createpc(pcno, ppcno) elif "deletepc" in cmd: cmd = cmd[9:-1] pcno = int(cmd) print "deleting process no:",pcno pnodes.deletepc(pcno) else: print "error command!" break
if name == "main": main()