python模拟shell交互创建文件、内存、进程管理系统

一、考核内容与要求

        创建新的进程,把进程放入调度队列中,然后使用调度算法进行进程调度,为调度的进程使用内存分配算法进行内存分配。再通过模拟实现一个基本的命令行界面对实现的调度算法和内存分配算法进行简单的验证,具体操作如下:
(1) 启动和引导(Bootloader)。编写一个简单的引导程序,引导程序将加载操作系统的内核。
(2) 内核(Kernel)。使用Python实现一个简化的内核,包括基本的内存管理、进程调度等。
(3) 文件系统(Filesystem)。实现一个简单的文件系统,支持基本的可执行文件创建与删除操作。创建的可执行文件只需要包含文件的大小,文件名字,文件需要运行的时间,文件优先级等进行调度需要的关键信息。
(4) 内存管理。实现一个简单的动态内存管理机制,包含最佳适配算法,最坏适配算法等。
(5) 进程管理。支持进程创建、调度和终止。可以使用Python的线程或进程模块来模拟。其中调度算法至少包含先进先出,优先级,高响应比,时间片轮转等算法。
(6)命令行界面(Shell)。模拟实现一个基本的命令行界面,用户可以在其中输入命令并执行。支持简单的命令。

二、函数具体要求:

run(执行文件,通过该命令根据文件的大小,运行时间,优先级等创建一个进程,参数为文件路径名,)下面是使用FCFS的进程调度顺序,运行时间,使用首次适应的内存分配算法后的内存释放起始位置,释放的内存块大小的运行结果。

createprocess(创建一个新的进程)
# 获取命令中第二个参数,即要创建进程所关联的文件路径,作为创建进程时的文件路径参数。 file_path = command[1]
# 获取命令中第三个参数,并将其转换为整数类型,作为创建进程时所需内存大小的参数。size = int(command[2])
# 获取命令中第四个参数,并将其转换为整数类型,作为创建进程运行所需时间的参数。run_time = int(command[3])
# 获取命令中第五个参数,并将其转换为整数类型,作为创建进程的优先级参数。priority = int(command[4])
 # 获取命令中第六个参数,并将其转换为整数类型,作为创建进程的开始时间参数。 start_time = int(command[5])
前面已经有5个进程了,可以再创建一些进程(个数自己定,这里又创建了4个,所以一共有9个进程)

ls(列出文件,列出当前目录下的所有目录和文件如果是目录在名字外加上‘[]’)

createfile(创建一个文件,参数为文件路径名,文件大小,文件运行时间,文件优先级等,先判断),deletefile(删除一个文件,参数为文件路径名,如果没有该文件,提示删除失败)

三、python代码实现

        3.1文件系统:

class FilesSystem:
    def __init__(self):
        self.root=[["bin"],["etc"],["home"],]

    def CreatFile(self,path,size,run_time,priority,start_time):
        parts=path.split('/')#parts将路径的各个目录分割开
        current_dir=self.root
        for part in parts[:-1]:
            part=part.split()
            found=False
            for element in current_dir:
                if isinstance(element, list) and element[0].strip()==part:
                    current_dir=element
                    found=True
                    break
            if not found:
                print(f"目录{part}不存在,无法创建文件。")
                return False
        file_name=parts[-1]
        file=File(file_name,size,run_time,priority,start_time)
        current_dir.append(file)
        print(f"文件{file_name}创建成功")
        return True

    def DeleteFile(self,path):
        parts = path.split('/')
        current_dir = self.root
        for part in parts[:-1]:
            part=part.split()
            found=False
            for element in current_dir:
                if isinstance(element, list) and element[0].strip() == part:
                    current_dir = element
                    found = True
                    break
            if not found:
                print(f"文件不存在,删除失败。")
                return False
        file_name=parts[-1]
        for element in current_dir:
            if isinstance(element,File) and element.name==file_name:

                current_dir.remove(element)
                print(f"文件{file_name}删除成功")
                return True
        print ("文件不存在,删除失败")
        return False

    def list_files(self,path):
        if path=='/':
            current_dir=self.root
        else:
            parts=path.split('/')
            current_dir=self.root
            for part in parts:
                found=False
                for element in current_dir:
                    if isinstance(element,list) and element[0].strip()==part:
                        current_dir=element
                        found=True
                        break
                if not found:
                    print(f"目录{part}不存在.")
                    return
        result=[]
        for element in current_dir:
            if isinstance(element,list):
                result.append(f"[{element[0]}]")
            else:
                result.append(element.name)
        print(" ".join(result))

    def find_file(self,path):
        parts=path.split('/')
        current_dir=self.root
        for part in parts[:-1]:
            found=False
            for element in current_dir:
                if isinstance(element, list) and element[0].strip() == part:
                    current_dir = element
                    found = True
                    break
            if not found:
                return None
        file_name=parts[-1]
        for element in current_dir:
            if isinstance(element,File) and element.name==file_name:
                return element
        return None

3.2内存管理系统

class MemoryManager:
    def __init__(self,memory_size):
        self.memory=[None]*memory_size


    def best_fit(self, size):
        best_start = -1
        best_size = float('inf')
        current_start = -1
        current_size = 0
        for i in range(len(self.memory)):#遍历所有内存空间
            if self.memory[i] is  None:#如果这片空间空,则更新current_start指针并统计内存块大小
                if current_start == -1:
                    current_start = i
                current_size += 1
            else:
                if size <= current_size < best_size:#如果内存块大小≥进程大小并且比最佳块更小,更新best_size和best_start。并赋初始值给current_size和current_start
                    best_size = current_size
                    best_start = current_start
                current_start = -1
                current_size = 0
        # 处理最后一个空闲块
        if current_start!= -1 and size <= current_size < best_size:
            best_size = current_size
            best_start = current_start
        if best_start!= -1:
            self.memory[best_start:best_start + size] = [True] * size
        return best_start


    def worst_fit(self, size):
        worst_start = -1
        worst_size = 0
        current_start = -1
        current_size = 0
        for i in range(len(self.memory)):
            if self.memory[i] is None:
                if current_start == -1:
                    current_start = i
                current_size += 1
            else:
                if current_size >= size and current_size > worst_size:
                    worst_size = current_size
                    worst_start = current_start
                current_start = -1
                current_size = 0
        # 处理最后一个空闲块
        if current_start!= -1 and current_size >= size and current_size > worst_size:
            worst_size = current_size
            worst_start = current_start
        if worst_start!= -1:
            self.memory[worst_start:worst_start + size] = [True] * size
        return worst_start



    def allocate_memory(self, size, algorithm="best_fit"):
        if algorithm == "best_fit":
            return self.best_fit(size)
        elif algorithm == "worst_fit":
            return self.worst_fit(size)

    def free_memory(self, start_index, size):
        self.memory[start_index:start_index + size] = [None] * size
        print(f"已释放起始位置为{start_index},大小为{size}的内存块")

3.3进程

3.3.1进程类

class Process:
    def __init__(self,file_path,pid,size,run_time,priority,start_time):
        self.pid = pid
        self.file_path = file_path
        self.size = size
        self.run_time = run_time
        self.priority = priority
        self.status = "READY"
        self.memory_start = None
        self.start_time = start_time

    def run(self):
        print(f"进程{self.pid}开始执行,运行时间:{self.run_time}")
        time.sleep(self.run_time)
        print(f"进程{self.pid}运行结束")
        self.status = "TERMINATED"

3.3.2进程管理系统

class ProcessManager():

    def __init__(self, memory_manager):
        self.process_queue_priority = queue.PriorityQueue()
        self.process_queue_hrrn = []
        self.process_list=[]
        self.pid_counter = 0
        self.memory_manager = memory_manager



    def createprocess(self,file_path,size,run_time,priority,start_time):
        self.pid_counter += 1
        process = Process(file_path, self.pid_counter, size, run_time, priority, start_time)
        start_index = self.memory_manager.allocate_memory(size, "best_fit")#调用best_fit算法为process分配内存空间
        if start_index!= -1:
            process.memory_start = start_index
            self.process_list.append(process)
            self.process_queue_hrrn.append(process)
            print(f"进程{process.pid}创建成功,对应文件路径:{process.file_path},内存已成功分配,起始位置:{start_index},分配大小:{size}")
            return process
        else:
            print("内存不足,无法创建进程")
            return None

    def deleteprocess(self,file_path):
        current_dir = self.process_list
        for process in current_dir:
            if file_path==process.file_path:
                self.memory_manager.free_memory(process.memory_start,process.size)
                print(f"文件{process.file_path}中的进程已删除")
                return True
        return False

    def schedule_hrrn(self,current_system_time):#高响应比优先算法
        processes_to_run = self.process_list
        #priority=0
        best_hrrn=-1
        best_process=None
        #self.process_queue_priority.put((priority,process))
        for process in processes_to_run:
            if kernel.system_time>=process.start_time:
                HRRN = ((current_system_time - process.start_time) + process.run_time) / process.run_time
                if HRRN>best_hrrn:
                    best_hrrn=HRRN
                    best_process=process
        kernel.system_time +=best_process.run_time
        print(f"进程{best_process.file_path}开始运行,运行开始时间:{kernel.system_time},服务时间:{best_process.run_time}")
        self.process_list.remove(best_process)#运行进程best_process并出队列
        return best_process

    def free_memory(self,process):
        if process.memory_start is not None:
            self.memory_manager.free_memory(process.memory_start,process.size)

时间片轮转算法的实现:

    def schedule_rr(self,current_system_time):#时间片轮转算法,时间片=1
        processes_to_run = self.process_list
        for process in processes_to_run:
            if kernel.system_time >= process.start_time:
                process.run_time-=1
                kernel.system_time+=1
                print(f"进程{process.pid}的运行时间还剩{process.run_time}")
                if process.run_time<=0:
                    print(f"进程{process.pid}已运行完毕,结束时间:{kernel.system_time}")
                    self.process_list.remove(process)

在run命令中只需要将

self.kernel.process_manager.schedule_hrrn(self.kernel.system_time)

红色内容变为rr

3.4shell模拟交互

class Shell():#模拟shell交互
    def __init__(self,kernel):
        self.kernel=kernel

    def run(self):
        while True:
            command=input("$ ").split()#输入命令
            if command[0]=="ls":#列出文件命令
                if len(command)>1:
                    self.kernel.file_system.list_files(command[1])#如果ls后有文件路径,则列出路径下的所有文件
                else:
                    self.kernel.file_system.list_files('/')

            elif command[0]=="createfile":#创建文件命令
                file_path = command[1]  # command的第二个传参为文件路径名
                size = int(command[2])  # command的第三个传参为文件大小
                run_time = int(command[3])  # 第四个为文件运行时间
                priority = int(command[4])  # 第五个为文件优先级
                start_time = int(command[5])  # 第六个为文件开始时间
                file=self.kernel.file_system.CreatFile(file_path, size, run_time, priority, start_time)
                if file:
                    print(f"文件{file_path}创建成功")

            elif command[0]=="deletefile":
                file_path = command[1]  # command的第二个传参为文件路径名
                if self.kernel.file_system.DeleteFile(file_path):
                    print(f"文件{file_path}删除成功")
                else:
                    print(f"无法删除{file_path}文件")

            elif command[0]=="run":
                while self.kernel.process_manager.process_list:#遍历进程列表
                    #self.kernel.system_time += 1
                    self.kernel.process_manager.schedule_hrrn(self.kernel.system_time)#调用hrrn算法
                    if not self.kernel.process_manager.process_list:
                        print("所有进程已经结束,可以继续输入命令。")


            elif command[0]=="createprocess":#command的第一个传参为命令(创建进程)
                file_path=command[1]#command的第二个传参为文件位置
                size=int(command[2])#command的第三个传参为进程大小
                run_time =int(command[3])#第四个为进程运行时间
                priority=int(command[4])#第五个为进程优先级
                start_time=int(command[5])#第六个为进程开始时间
                file=self.kernel.file_system.find_file(file_path)
                if file:
                    process=self.kernel.process_manager.createprocess(file_path,size,run_time,priority,start_time)
                    if process:
                        print("进程创建成功")
                    else:
                        print("因内存不足,无法创建进程")
                else:
                    print("文件不存在,无法创建进程")
            elif command[0]=="deleteprocess":
                file_path = command[1]  # command的第二个传参为进程所在文件的路径
                if self.kernel.process_manager.deleteprocess(file_path):
                    print(f"文件{file_path}内的进程删除成功")
                else:
                    print(f"无法删除{file_path}文件内的进程")

            elif command[0]=="exit":
                break

            else:
                print("无效命令,请重新输入")

其中deleteprocess命令是需要的,这样可以对内存中的进程删除,为新的进程留出不连续的空位,来证明最佳适应算法和最坏适应算法的正确性。 

3.5main函数

if __name__ == '__main__':
    kernel=bootloader()
    file_paths = ["File1", "File2", "File3", "File4", "File5"]
    file_sizes = [10, 60, 30, 40, 50]
    run_times = [3, 6, 4, 5, 2]
    priorities = [1, 2, 3, 4, 5]
    start_times = [0, 2, 4, 6, 8]
    for i in range(5):
        if kernel.file_system.CreatFile(file_paths[i],file_sizes[i],run_times[i],priorities[i],start_times[i]):
            file=kernel.file_system.find_file(file_paths[i])
            if file:
                kernel.process_manager.createprocess(file_paths[i],file_sizes[i],run_times[i],priorities[i],start_times[i])#依次为进程1~5分配内存空间
    kernel.start()

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值