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 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 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 terminate(self, pid=None): """ If no pid given, terminates active process in CPU. Else, terminates process with given pid. If active process is terminated, moves head of Ready Queue to CPU. Precondition: pid is a valid PID for a process in the ready queue or CPU """ proc = None if self.active: # Terminate active process if no pid given or if active process has # given pid if not pid or self.active.pid == pid: proc = self.active self.ready_to_CPU() self.record_burst(proc) else: # Look for process in ready queue and remove proc = PriorityQueue.pop(self, pid) # Prompt for time since last interrupt # Update burst time for active process elapsed = io.get_valid_int("Time since last interrupt") self.active.update_burst_time(elapsed) # Print stats print "\n" + "{:-^78}".format(" Terminated Process Report ") print "PID: {:<4} Avg CPU Burst Time: {:<5} Total CPU Time: {:<5}".format( proc.pid, proc.avg_burst_time(), proc.tot_burst_time()).center(78, " ") del proc else: raise IndexError
def enqueue(self, proc, updateburst=True): """ Adds process to back of ready queue and updates PCB status/location """ if not self.active: # No processes in CPU, process goes straight to CPU # No need to prompt for time proc.set_proc_loc(self._dev_name) self.active = proc else: if updateburst: # Prompt for time since last interrupt elapsed = io.get_valid_int("Time since last interrupt") # Update burst time for current process self.active.update_burst_time(elapsed) # Insert into ready queue proc.set_proc_loc("ready") PriorityQueue.enqueue(self, proc) # Move active process to ready queue if it now has a higher # remaining burst time left than any process in the ready queue if PriorityQueue.head(self) < self.active: p = PriorityQueue.dequeue(self) self.active.set_proc_loc("ready") p.set_proc_loc("CPU") PriorityQueue.enqueue(self, self.active) self.active = p print proc.status()
def set_cylinder_params(self, max_num_cylinders): """ Prompts user for which disk drive cylinder to access, validates input and sets appropriate system call parameter. Precondition: Process is in disk drive """ while self.params["cyl"] == None: c = io.get_valid_int("Cylinder") if c > max_num_cylinders: print "Invalid cylinder number. Please try again." else: self.params["cyl"] = c
def generate(): """ Generates all system device instances based on user input. Returns list of all system devices. """ print io.sys_mode("System Setup") # Dictionary of type of devices and how many devices of each type system_device_types = {} print "For each device type, please specify the number of devices." for d in valid_device_types: # Add device type & how many of each type system_device_types[d] = None system_device_types[d] = io.get_valid_int(d) print io.sys_mode("Initialize Disk Drive",'-') # List of all individual devices in system system_devices = [] for dev_type, num_of_dev in system_device_types.iteritems(): name_prefix = dev_type[0].lower() # Create new device, add to list of system_devices for i in range(num_of_dev): name = name_prefix + str(i+1) if (dev_type == "Disk Drive"): cyl = io.get_valid_int("Num of cylinders for " + name) system_devices.append(devices.DiskDrive(name,cyl)) else: system_devices.append(devices.Device(name, dev_type)) return system_devices
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 record_burst(self, proc): """ Get and update burst time for process proc """ burst = io.get_valid_int("Time since last interrupt") proc.record_burst_time(burst)