def kill(self, pid): try: # Check to see if positive whole number pid = int(pid) if not isinstance(pid, (int, long)) or pid <= 0: raise ValueError # Look for process in devices and terminate when found if self.cpu.contains(pid): self.cpu.terminate(pid) else: for dev in self.all_devices: if dev.contains(pid): dev.terminate(pid) if self.cpu.active: elapsed = io.get_valid_int( "Time since last interrupt") self.cpu.active.update_burst_time(elapsed) # Deallocate memory for process and reallocate memory # No need to update burst time new_procs = self.lts.terminate(pid) if new_procs: for p in new_procs: self.cpu.enqueue(p, False) except ValueError as e: print io.err("Please enter a valid positive integer") except InvalidProcess: # Process not found in job pool or in memory print io.err("Process does not exist")
def set_read_write_params(self, dev_type): """ Sets system call params for read/write and file length (if write) """ if (dev_type.lower() == "printer"): self.params["rw"] = "w" else: while self.params["rw"] == None: rw = raw_input("Read or Write? >>> ") if rw.lower() in ["r", "read"]: self.params["rw"] = "r" elif rw.lower() in ["w", "write"]: self.params["rw"] = "w" else: print io.err("Invalid read/write parameters") print "Please enter either 'r', 'read', 'w' or 'write'" if self.params["rw"] == "w": set_len = False while not set_len: l = io.get_valid_int("File Length") if l + self.params["log"] <= self.proc_size: self.params["len"] = l set_len = True else: print io.err("Invalid length (too long)")
def do_a(self, args): """ User input: A Get and validate process size. If process is larger than total memory or max process size, reject process. Else, create a new process. If enough memory, add to ready queue, else go to job pool. """ procsize = io.get_valid_int("Process size") if procsize > self.total_mem_size: print io.err("Proccess cannot be larger than total memory") elif procsize > self.max_proc_size: print io.err( "Proccess cannot be larger than maximum process size of " + str(self.max_proc_size)) else: # Create new process self.pid_count += 1 pages = int(ceil(procsize / self.page_size)) new_proc = PCB(self.pid_count, procsize, pages, self.page_size, self.alpha, self.tau) # If enough memory, new process can run, else goes to job pool if self.lts.schedule(new_proc): self.cpu.enqueue(new_proc)
def bank_login(bank): msg = """\ Login ----- Please enter your password: """ password = io.get_password(msg) try: account = bank.get_account(password) account_menu(account) bank.put_account(account) except BankException as ex: io.err(ex) return True
def default(self, args): """ Default response to user input: Requesting a device, killing a process or invalid command """ # User command: KILL. if self.lastcmd.lower()[0] is "k": return self.kill(self.lastcmd.lower()[1:]) # User requests or ends a device device_found = False for dev in self.all_devices: if dev.is_device_name(self.lastcmd.lower()): device_found = True if self.lastcmd.islower(): # SYSTEM CALL (lowercase input) # Get active process from CPU, replace with head of ready queue try: proc = self.cpu.dequeue() except IndexError: print io.nothing_in_cpu() break # Prompt user for and set PCB params print io.sys_mode("Set system call parameters") proc.set_syst_call_params() proc.set_read_write_params(dev.get_dev_type()) if (dev.get_dev_type().lower() == "disk drive"): proc.set_cylinder_params(dev.get_num_cylinders()) print io.sys_mode("System call parameters set") # Add process to back of device queue dev.enqueue(proc) else: # INTERRUPT (uppercase input) # Process at head of device queue complete # Remove from device queue, move to back of ready queue try: proc = dev.dequeue() print "%s completed %s" % (dev, proc) self.cpu.enqueue(proc) except IndexError: print io.err("{!s} queue is empty".format(dev)) if not device_found: print io.invalid_command()
def set_syst_call_params(self): """ Sets system call params for file name & starting memory location """ self.params["file"] = raw_input("File Name >>> ") set_loc = False while not set_loc: l = io.get_valid_hex("Starting Memory Location in Hex") if l < self.proc_size: set_loc = True offset = int(l % self.pg_size) pg = int(floor(l / self.pg_size)) self.params["log"] = l self.params["phys"] = (self.pg_size * self.page_table[pg]) + offset else: print io.err("Invalid starting memory location")
def do_s(self, args): """ User input: S Snapshot mode: Displays processes in queue specified by user """ # Request device type from user print io.sys_mode("Snapshot Mode") print "Enter the first letter of a device type to view the queues of all devices of" print "that type." + "\n" type_to_snapshot = raw_input("Device Type >>> ").lower() # Show active process in CPU & processes in ready queue if type_to_snapshot == "r": self.cpu.snapshot() self.lts.show_job_pool() # Show what's in memory elif type_to_snapshot == "m": self.lts.snapshot() # Show processes in device elif type_to_snapshot in [ d.get_dev_type()[0].lower() for d in self.all_devices ]: for dev in self.all_devices: if type_to_snapshot == dev.get_dev_type()[0].lower(): dev.snapshot() else: print io.err("Unknown device type") # Print system stats self.print_system_stats() print io.sys_mode("Exiting Snapshot Mode")
def __init__(self, completekey=None): cmd.Cmd.__init__(self, completekey=None) self.prompt = " >>> " ## SYS GEN PHASE: Set up queues & devices in system self.all_devices = sys_gen.generate() # Set up history parameter alpha & initial bust estimate tau with valid values print io.sys_mode("Initialize CPU Scheduling Parameters", '-') set_alpha = False while not set_alpha: try: a = float(raw_input("History Parameter >>> ")) if a < 0 or a > 1: raise ValueError self.alpha = a set_alpha = True except ValueError: print io.err("Please enter a number between 0 and 1") except OverflowError: print io.err("Overflow error: Please enter a shorter number") self.tau = io.get_valid_int("Initial Burst Estimate") # Set up memory size & page size print io.sys_mode("Initialize Memory Parameters", '-') # Get page & mem size. Verify page size is a power of two and a factor of memory size. set_size = False while not set_size: self.total_mem_size = io.get_valid_int("Total Memory Size") self.page_size = io.get_pow_two("Page Size") if self.total_mem_size % self.page_size == 0: set_size = True else: print io.err("Memory size must be divisible by page size") # Get & verify maximum process size set_proc_size = False while not set_proc_size: self.max_proc_size = io.get_valid_int("Maximum Process Size") if self.max_proc_size <= self.total_mem_size: set_proc_size = True else: print io.err( "Maximum process size cannot be larger than total memory") # Set up long term scheduler. This will also set up RAM & job pool self.lts = LongTermScheduler(self.total_mem_size, self.page_size) # Set up CPU & PID self.cpu = devices.CPU() self.pid_count = 0 # Set up system stats self.completed = 0 self.total_cpu_time = 0 self.avg_cpu_time = 0 # Print out list of devices to console print io.sys_mode("System Generation Complete") print "Your system is now running with the following devices: " print io.ruler(38) print "{:<10}{:<28}".format("DEV NAME", "DEV TYPE") print io.ruler(38) for dev in self.all_devices: print "{:<10}{:<28}".format(dev.get_dev_name(), dev.get_dev_type()) ## Now in the RUNNING PHASE print io.sys_mode("System running") print "Input a command to start a process in the system." print "-- Type H or h to view a list of valid commands" + "\n"
def account_withdraw(account): try: account.withdraw(io.get_amount('Withdraw: ')) except AccountException as ex: io.err(ex) return True