system/command_interpreter.py
2024-12-05 19:45:11 +08:00

251 lines
8.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
from typing import Dict, Any, Callable
from process_management import Process, ProcessState
from resource_management import ResourceType
from memory_management import MemoryAllocationStrategy
class CommandInterpreter:
"""
解释并执行模拟操作系统的命令
"""
def __init__(self):
# 命令映射
self.commands: Dict[str, Callable] = {
'ALLOCATE': self.allocate_memory,
'REQUEST_RESOURCE': self.request_resource,
'RELEASE_RESOURCE': self.release_resource,
'CREATE_FILE': self.create_file,
'DELETE_FILE': self.delete_file,
'READ_FILE': self.read_file,
'WRITE_FILE': self.write_file,
'DISK_SEEK': self.optimize_disk_seek,
}
def execute_command(self, command: str, process: Process, os_system: Any):
"""
解析并执行给定进程的命令
:param command: 要执行的命令字符串
:param process: 执行命令的进程
:param os_system: 操作系统引用
"""
# 将命令分词
tokens = command.strip().split()
if not tokens:
return
# 提取命令和参数
cmd = tokens[0].upper()
args = tokens[1:]
# 查找并执行相应的命令
if cmd in self.commands:
try:
self.commands[cmd](process, os_system, *args)
except Exception as e:
print(f"执行命令 {cmd} 时出错: {e}")
else:
print(f"未知命令: {cmd}")
def allocate_memory(self, process: Process, os_system: Any, size: str = None, strategy: str = None):
"""
为进程分配内存
:param process: 请求内存分配的进程
:param os_system: 操作系统引用
:param size: 要分配的内存大小
:param strategy: 内存分配策略
"""
# 将大小转换为整数
try:
memory_size = int(size or 1024) # 如果未指定默认1KB
except ValueError:
memory_size = 1024
# 确定分配策略
if strategy:
strategy = strategy.lower()
allocation_strategies = {
'first': MemoryAllocationStrategy.FIRST_FIT,
'best': MemoryAllocationStrategy.BEST_FIT,
'worst': MemoryAllocationStrategy.WORST_FIT
}
os_system.memory_manager.allocation_strategy = allocation_strategies.get(
strategy,
MemoryAllocationStrategy.FIRST_FIT
)
# 分配内存
start_address = os_system.memory_manager.allocate_memory(
process.pid,
memory_size
)
if start_address is not None:
print(f"进程 {process.pid} 分配了 {memory_size} 字节,地址为 {start_address}")
else:
print(f"进程 {process.pid} 内存分配失败")
def request_resource(self, process: Process, os_system: Any, resource_type: str):
"""
请求系统资源
:param process: 请求资源的进程
:param os_system: 操作系统引用
:param resource_type: 要请求的资源类型
"""
# 将字符串映射到ResourceType
resource_types = {
'PRINTER': ResourceType.PRINTER,
'DISK': ResourceType.DISK,
'NETWORK': ResourceType.NETWORK
}
# 验证并请求资源
try:
res_type = resource_types[resource_type.upper()]
success = os_system.resource_manager.request_resource(process.pid, res_type)
if success:
print(f"进程 {process.pid} 成功分配了 {resource_type}")
else:
print(f"进程 {process.pid} 资源 {resource_type} 分配失败")
except KeyError:
print(f"无效的资源类型: {resource_type}")
def release_resource(self, process: Process, os_system: Any, resource_type: str):
"""
释放先前分配的资源
:param process: 释放资源的进程
:param os_system: 操作系统引用
:param resource_type: 要释放的资源类型
"""
# 将字符串映射到ResourceType
resource_types = {
'PRINTER': ResourceType.PRINTER,
'DISK': ResourceType.DISK,
'NETWORK': ResourceType.NETWORK
}
try:
res_type = resource_types[resource_type.upper()]
# 查找并释放分配给该进程的此类资源
allocations = os_system.resource_manager.resource_allocations.get(process.pid, set())
resources_to_release = [
res for res in allocations
if res.type == res_type
]
for resource in resources_to_release:
os_system.resource_manager.release_resource(process.pid, resource)
print(f"进程 {process.pid} 释放了 {resource_type} 资源")
except KeyError:
print(f"无效的资源类型: {resource_type}")
def create_file(self, process: Process, os_system: Any, filename: str):
"""
在文件系统中创建文件
:param process: 创建文件的进程
:param os_system: 操作系统引用
:param filename: 要创建的文件名
"""
try:
success = os_system.file_system.create_file(filename, process.pid)
if success:
print(f"进程 {process.pid} 创建了文件: {filename}")
else:
print(f"文件 {filename} 创建失败")
except Exception as e:
print(f"创建文件 {filename} 时出错: {e}")
def delete_file(self, process: Process, os_system: Any, filename: str):
"""
从文件系统中删除文件
:param process: 删除文件的进程
:param os_system: 操作系统引用
:param filename: 要删除的文件名
"""
try:
success = os_system.file_system.delete_file(filename, process.pid)
if success:
print(f"进程 {process.pid} 删除了文件: {filename}")
else:
print(f"文件 {filename} 删除失败")
except Exception as e:
print(f"删除文件 {filename} 时出错: {e}")
def read_file(self, process: Process, os_system: Any, filename: str, offset: str = '0', size: str = None):
"""
从文件系统中读取文件
:param process: 读取文件的进程
:param os_system: 操作系统引用
:param filename: 要读取的文件名
:param offset: 文件起始字节偏移量
:param size: 要读取的字节数
"""
try:
# 将偏移量和大小转换为整数
offset_bytes = int(offset)
read_size = int(size) if size else None
content = os_system.file_system.read_file(
filename,
process.pid,
offset_bytes,
read_size
)
print(f"进程 {process.pid} 从文件 {filename} 读取: {content}")
except Exception as e:
print(f"读取文件 {filename} 时出错: {e}")
def write_file(self, process: Process, os_system: Any, filename: str, offset: str = '0', content: str = ''):
"""
向文件系统中的文件写入内容
:param process: 写入文件的进程
:param os_system: 操作系统引用
:param filename: 要写入的文件名
:param offset: 文件起始字节偏移量
:param content: 要写入的内容
"""
try:
# 将偏移量转换为整数
offset_bytes = int(offset)
success = os_system.file_system.write_file(
filename,
process.pid,
offset_bytes,
content
)
if success:
print(f"进程 {process.pid} 写入了文件 {filename}")
else:
print(f"文件 {filename} 写入失败")
except Exception as e:
print(f"写入文件 {filename} 时出错: {e}")
def optimize_disk_seek(self, process: Process, os_system: Any, *seek_params):
"""
优化磁盘寻道操作
:param process: 请求磁盘寻道优化的进程
:param os_system: 操作系统引用
:param seek_params: 磁盘寻道优化的参数
"""
try:
# 调用磁盘管理器的寻道优化方法
os_system.disk_manager.optimize_seek_operations()
print(f"进程 {process.pid} 请求了磁盘寻道优化")
except Exception as e:
print(f"磁盘寻道优化失败: {e}")