操作系统模拟实验(进程的撤销与创建)
一个很简陋的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()