跳到主要内容 C++ 简化版操作系统模拟器 v5.0 完整源码 | 极客日志
C++ 算法
C++ 简化版操作系统模拟器 v5.0 完整源码 本文提供了一个基于 C++ 的简化版操作系统模拟器 v5.0 源码。项目包含内存管理模块、文件系统结构、进程管理与调度算法(支持 FCFS、优先级、SJF、时间片轮转)、内核系统调用及用户空间 Shell。实现了二进制序列化与反序列化功能,支持系统状态保存与加载,具备自动保存机制。代码结构清晰,适合学习操作系统核心原理。
苹果系统 发布于 2026/3/28 更新于 2026/4/14 1 浏览#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include <condition_variable>
#include
#include
#include
#include
#include
#include
#include
using namespace std;
// ==================== 线程安全工具 ====================
class ScopedLock {
private:
std::mutex& mtx_;
public:
ScopedLock(std::mutex& mtx) : mtx_(mtx) { mtx_.lock(); }
~ScopedLock() { mtx_.unlock(); }
};
// ==================== 二进制序列化工具 ====================
class BinarySerializer {
private:
vector buffer;
size_t pos;
public:
BinarySerializer() : pos(0) {}
BinarySerializer(const vector& data) : buffer(data), pos(0) {}
template <typename T>
void writeType (const T& value) {
size_t size = sizeof (T);
buffer.resize (buffer.size () + size);
memcpy (&buffer[pos], &value, size);
pos += size;
}
template <typename T>
T readType () {
if (pos + sizeof (T) > buffer.size ()) {
throw runtime_error ("读取数据越界" );
}
T value;
memcpy (&value, &buffer[pos], sizeof (T));
pos += sizeof (T);
return value;
}
void writeString (const string& str) {
uint32_t len = < >(str. ());
(len);
buffer. (buffer. () + len);
(&buffer[pos], str. (), len);
pos += len;
}
{
len = < >();
(pos + len > buffer. ()) {
( );
}
;
pos += len;
str;
}
{
( < >(value ? : ));
}
{
< >() == ;
}
{
buffer;
}
{
pos;
}
{
(new_pos > buffer. ()) {
( );
}
pos = new_pos;
}
{
pos = ;
}
{
buffer. ();
pos = ;
}
微信扫一扫,关注极客日志 微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
Markdown 转 HTML 将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
HTML 转 Markdown 将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
JSON 压缩 通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online
static_cast
uint32_t
length
writeType
resize
size
memcpy
c_str
string readString ()
uint32_t
readType
uint32_t
if
size
throw
runtime_error
"读取字符串越界"
string str (&buffer[pos], len)
return
void writeBool (bool value)
writeType
static_cast
uint8_t
1
0
bool readBool ()
return
readType
uint8_t
1
vector<char > getData () const
return
size_t getPosition () const
return
void setPosition (size_t new_pos)
if
size
throw
runtime_error
"设置位置越界"
void reset ()
0
void clear ()
clear
0
// ==================== 内存管理模块 ====================
struct MemoryBlock {
int start_address;
int size;
bool allocated;
int owner_pid;
string description;
MemoryBlock (int start, int s, bool alloc = false, int owner = -1 , const string& desc)
: start_address (start), size (s), allocated (alloc), owner_pid (owner), description (desc) {}
void serialize (BinarySerializer& serializer) const {
serializer.writeType (start_address);
serializer.writeType (size);
serializer.writeBool (allocated);
serializer.writeType (owner_pid);
serializer.writeString (description);
}
static MemoryBlock deserialize (BinarySerializer& serializer) {
int start = serializer.readType <int>();
int size = serializer.readType <int>();
bool allocated = serializer.readBool ();
int owner = serializer.readType <int>();
string desc = serializer.readString ();
return MemoryBlock (start, size, allocated, owner, desc);
}
class MemoryManager {
private:
vector memory_blocks;
int total_memory;
mutable std::mutex memory_mutex;
public:
MemoryManager(int total_mem = 1024) : total_memory(total_mem) {
memory_blocks.emplace_back(0, total_memory, false);
}
int allocateMemory(int size, int pid, const string& desc) {
ScopedLock lock(memory_mutex)
for (size_t i = 0
if (!memory_blocks[i] .allocated && memory_blocks[i] .size >= size) {
if (memory_blocks[i] .size > size) {
MemoryBlock new_free_block(memory_blocks[i] .start_address + size,
memory_blocks[i] .size - size,
false)
memory_blocks.insert(memory_blocks.begin() + i + 1, new_free_block)
}
memory_blocks[i] .size = size
memory_blocks[i] .allocated = true
memory_blocks[i] .owner_pid = pid
memory_blocks[i] .description = desc
return memory_blocks[i] .start_address
}
}
return -1
}
bool freeMemory(int address) {
ScopedLock lock(memory_mutex)
for (size_t i = 0
if (memory_blocks[i] .start_address == address && memory_blocks[i].allocated) {
memory_blocks[i] .allocated = false
memory_blocks[i] .owner_pid = -1
memory_blocks[i] .description = ""
// 合并相邻空闲块
if (i > 0 && !memory_blocks[i-1] .allocated) {
memory_blocks[i-1] .size += memory_blocks[i] .size
memory_blocks.erase(memory_blocks.begin() + i)
i--
}
if (i < memory_blocks.size() - 1 && !memory_blocks[i+1] .allocated) {
memory_blocks[i] .size += memory_blocks[i+1] .size
memory_blocks.erase(memory_blocks.begin() + i + 1)
}
return true
}
}
return false
}
vector<MemoryBlock> getMemoryStatus() const {
ScopedLock lock(memory_mutex)
return memory_blocks
}
int getTotalFreeMemory() const {
ScopedLock lock(memory_mutex)
int free = 0
for (const auto& block : memory_blocks) {
if (!block.allocated) free += block.size
}
return free
}
int getTotalUsedMemory() const {
ScopedLock lock(memory_mutex)
int used = 0
for (const auto& block : memory_blocks) {
if (block.allocated) used += block.size
}
return used
}
// 序列化内存状态
void serialize(BinarySerializer& serializer) const {
ScopedLock lock(memory_mutex)
serializer.writeType(static_cast<uint32_t>(memory_blocks.size()))
serializer.writeType(total_memory)
for (const auto& block : memory_blocks) {
block.serialize(serializer)
}
}
// 反序列化内存状态
void deserialize(BinarySerializer& serializer) {
ScopedLock lock(memory_mutex)
memory_blocks.clear()
uint32_t block_count = serializer.readType<uint32_t>()
total_memory = serializer.readType<int>()
for (uint32_t i = 0
memory_blocks.push_back(MemoryBlock::deserialize(serializer))
}
}
// ==================== 文件权限管理 ====================
enum class FilePermission {
NONE = 0,
READ = 1,
WRITE = 2,
EXECUTE = 4
};
inline FilePermission operator|(FilePermission a, FilePermission b) {
return static_cast(static_cast(a) | static_cast(b));
}
inline bool operator&(FilePermission a, FilePermission b) {
return (static_cast(a) & static_cast(b)) != 0;
}
struct FilePermissions {
FilePermission owner;
FilePermission group;
FilePermission others;
int owner_id;
int group_id;
FilePermissions(int owner_id = 0 , int group_id = 0 )
: owner_id(owner_id), group_id(group_id) {
owner = FilePermission::READ | FilePermission::WRITE
group = FilePermission::READ
others = FilePermission::READ
}
bool canRead(int user_id, int user_group_id) const {
if (user_id == owner_id) return (owner & FilePermission::READ)
if (user_group_id == group_id) return (group & FilePermission::READ)
return (others & FilePermission::READ)
}
bool canWrite(int user_id, int user_group_id) const {
if (user_id == owner_id) return (owner & FilePermission::WRITE)
if (user_group_id == group_id) return (group & FilePermission::WRITE)
return (others & FilePermission::WRITE)
}
bool canExecute(int user_id, int user_group_id) const {
if (user_id == owner_id) return (owner & FilePermission::EXECUTE)
if (user_group_id == group_id) return (group & FilePermission::EXECUTE)
return (others & FilePermission::EXECUTE)
}
// 序列化权限
void serialize(BinarySerializer& serializer) const {
serializer.writeType(static_cast<int>(owner))
serializer.writeType(static_cast<int>(group))
serializer.writeType(static_cast<int>(others))
serializer.writeType(owner_id)
serializer.writeType(group_id)
}
// 反序列化权限
void deserialize(BinarySerializer& serializer) {
owner = static_cast<FilePermission>(serializer.readType<int>())
group = static_cast<FilePermission>(serializer.readType<int>())
others = static_cast<FilePermission>(serializer.readType<int>())
owner_id = serializer.readType<int>()
group_id = serializer.readType<int>()
}
// ==================== 文件系统结构(目录和文件) ====================
class FileSystemNode {
public:
string name;
bool is_directory;
string content;
FilePermissions permissions;
time_t create_time;
time_t modify_time;
mutable std::mutex node_mutex;
FileSystemNode(const string& n, bool is_dir = false , int owner_id = 0 , int group_id = 0 )
: name(n), is_directory(is_dir), permissions(owner_id, group_id) {
time_t now = time(nullptr)
create_time = now
modify_time = now
}
virtual ~FileSystemNode() = default
virtual string getType() const {
return is_directory ? "目录" : "文件"
}
// 序列化节点
virtual void serialize(BinarySerializer& serializer) const {
ScopedLock lock(node_mutex)
serializer.writeString(name)
serializer.writeBool(is_directory)
serializer.writeString(content)
permissions.serialize(serializer)
serializer.writeType(static_cast<uint64_t>(create_time))
serializer.writeType(static_cast<uint64_t>(modify_time))
}
// 反序列化节点
virtual void deserialize(BinarySerializer& serializer) {
ScopedLock lock(node_mutex)
name = serializer.readString()
is_directory = serializer.readBool()
content = serializer.readString()
permissions.deserialize(serializer)
create_time = static_cast<time_t>(serializer.readType<uint64_t>())
modify_time = static_cast<time_t>(serializer.readType<uint64_t>())
}
class FileNode : public FileSystemNode {
public:
FileNode(const string& n, int owner_id = 0, int group_id = 0)
: FileSystemNode(n, false, owner_id, group_id) {}
string getType () const override {
return "文件" ;
}
class DirectoryNode : public FileSystemNode {
public:
map<string, shared_ptr> children;
DirectoryNode (const string& n, int owner_id = 0 , int group_id = 0 )
: FileSystemNode (n, true , owner_id, group_id) {}
string getType () const override {
return "目录" ;
}
void serialize (BinarySerializer& serializer) const override {
FileSystemNode::serialize (serializer);
ScopedLock lock (node_mutex) ;
serializer.writeType (static_cast <uint32_t >(children.size ()));
for (const auto & child : children) {
child.second->serialize (serializer);
}
}
void deserialize (BinarySerializer& serializer) override {
FileSystemNode::deserialize (serializer);
ScopedLock lock (node_mutex) ;
children.clear ();
uint32_t child_count = serializer.readType <uint32_t >();
for (uint32_t i = 0 ; i < child_count; i++) {
size_t current_pos = serializer.getPosition ();
string name = serializer.readString ();
bool is_dir = serializer.readBool ();
serializer.setPosition (current_pos);
shared_ptr<FileSystemNode> node;
if (is_dir) {
node = make_shared <DirectoryNode>("" );
} else {
node = make_shared <FileNode>("" );
}
node->deserialize (serializer);
children[node->name] = node;
}
}
class FileSystem {
private:
shared_ptr root;
int current_user_id;
int current_group_id;
mutable std::mutex fs_mutex;
vector <string > splitPath (const string & path) const {
vector <string > parts;
stringstream ss (path) ;
string part;
while (getline(ss, part, '/' )) {
if (!part.empty()) parts.push_back(part);
}
return parts;
}
shared_ptr <FileSystemNode> getNode (const string & path) const {
if (path.empty() || path == "/" ) return root;
vector <string > parts = splitPath(path);
shared_ptr <FileSystemNode> current = root;
for (const auto & part : parts) {
ScopedLock lock (current->node_mutex) ;
if (!current->is_directory) return nullptr;
auto dir = dynamic_pointer_cast<DirectoryNode>(current);
if (dir->children.find(part) == dir->children.end()) {
return nullptr;
}
current = dir->children[part];
}
return current;
}
shared_ptr <DirectoryNode> getParentDirectory (const string & path) const {
size_t last_slash = path.rfind('/' );
if (last_slash == string ::npos) return root;
string parent_path = path.substr(0 , last_slash);
if (parent_path.empty()) return root;
auto node = getNode(parent_path);
if (node && node->is_directory) {
return dynamic_pointer_cast<DirectoryNode>(node);
}
return nullptr;
}
public:
FileSystem() : current_user_id(0), current_group_id(0) {
root = make_shared("/", 0, 0);
}
void setCurrentUser (int user_id, int group_id) {
current_user_id = user_id;
current_group_id = group_id;
}
bool createFile (const string& path, const string& content) {
ScopedLock lock (fs_mutex);
auto parent = getParentDirectory (path);
if (!parent) return false;
string filename = path .substr (path.rfind('/') + 1 );
ScopedLock parent_lock (parent->node_mutex);
if (parent->children.find(filename) != parent->children.end ()) {
return false;
}
if (!parent->permissions.canWrite(current_user_id, current_group_id)) {
return false;
}
auto file = make_shared<FileNode>(filename, current_user_id, current_group_id);
file->content = content ;
parent->children[filename] = file;
parent->modify_time = time (nullptr);
return true;
}
bool createDirectory (const string& path) {
ScopedLock lock (fs_mutex);
auto parent = getParentDirectory (path);
if (!parent) return false;
string dirname = path .substr (path.rfind('/') + 1 );
ScopedLock parent_lock (parent->node_mutex);
if (parent->children.find(dirname) != parent->children.end ()) {
return false;
}
if (!parent->permissions.canWrite(current_user_id, current_group_id)) {
return false;
}
auto dir = make_shared<DirectoryNode>(dirname, current_user_id, current_group_id);
parent->children[dirname] = dir;
parent->modify_time = time (nullptr);
return true;
}
bool deleteNode (const string& path) {
ScopedLock lock (fs_mutex);
auto parent = getParentDirectory (path);
if (!parent) return false;
string name = path .substr (path.rfind('/') + 1 );
ScopedLock parent_lock (parent->node_mutex);
auto it = parent->children.find (name);
if (it == parent->children.end()) {
return false;
}
if (!parent->permissions.canWrite(current_user_id, current_group_id)) {
return false;
}
parent->children.erase (it);
parent->modify_time = time (nullptr);
return true;
}
string readFile (const string& path) const {
ScopedLock lock (fs_mutex);
auto node = getNode (path);
if (!node || node->is_directory) {
return "错误:文件不存在或路径指向目录";
}
ScopedLock node_lock (node->node_mutex);
if (!node->permissions.canRead(current_user_id, current_group_id)) {
return "错误:没有读取权限";
}
return node->content ;
}
bool writeFile (const string& path, const string& content) {
ScopedLock lock (fs_mutex);
auto node = getNode (path);
if (!node || node->is_directory) {
return false;
}
ScopedLock node_lock (node->node_mutex);
if (!node->permissions.canWrite(current_user_id, current_group_id)) {
return false;
}
node->content = content ;
node->modify_time = time (nullptr);
return true;
}
bool changePermissions (const string& path, int new_perms) {
ScopedLock lock (fs_mutex);
auto node = getNode (path);
if (!node) return false;
ScopedLock node_lock (node->node_mutex);
if (current_user_id != 0 && current_user_id != node->permissions.owner_id) {
return false;
}
node->permissions.owner = static_cast<FilePermission>((new_perms / 100 ) % 10 );
node->permissions.group = static_cast<FilePermission>((new_perms / 10 ) % 10 );
node->permissions.others = static_cast<FilePermission>(new_perms % 10 );
node->modify_time = time (nullptr);
return true;
}
string listDirectory (const string& path = "/") const {
ScopedLock lock (fs_mutex);
auto node = getNode (path);
if (!node || !node->is_directory) {
return "错误:目录不存在";
}
ScopedLock node_lock (node->node_mutex);
auto dir = dynamic_pointer_cast<DirectoryNode>(node);
ostringstream oss;
oss << "目录内容:" << path << "\n";
oss << string (50 , '-') << "\n";
oss << left << setw (25 ) << "名称"
<< setw (10 ) << "类型"
<< setw (10 ) << "大小"
<< setw (8 ) << "权限"
<< "修改时间\n";
oss << string (50 , '-') << "\n";
if (path != "/") {
oss << left << setw (25 ) << ".."
<< setw (10 ) << "目录"
<< setw (10 ) << "-"
<< setw (8 ) << "------"
<< "\n";
}
for (const auto& child : dir->children) {
ScopedLock child_lock (child.second->node_mutex);
string perms;
perms += (child.second->permissions.owner & FilePermission::READ) ? 'r ' : '-' ;
perms += (child.second->permissions.owner & FilePermission::WRITE) ? 'w' : '-' ;
perms += (child.second->permissions.owner & FilePermission::EXECUTE) ? 'x ' : '-' ;
perms += (child.second->permissions.group & FilePermission::READ) ? 'r ' : '-' ;
perms += (child.second->permissions.group & FilePermission::WRITE) ? 'w' : '-' ;
perms += (child.second->permissions.group & FilePermission::EXECUTE) ? 'x ' : '-' ;
perms += (child.second->permissions.others & FilePermission::READ) ? 'r ' : '-' ;
perms += (child.second->permissions.others & FilePermission::WRITE) ? 'w' : '-' ;
perms += (child.second->permissions.others & FilePermission::EXECUTE) ? 'x ' : '-' ;
char time_buf[20] ;
strftime (time_buf, sizeof(time_buf), "%Y -%m-%d %H:%M",
localtime(&child.second->modify_time));
oss << left << setw(25) << child.first
<< setw(10) << child.second->getType()
<< setw(10) << (child.second->is_directory ? " -" :
to_string(child.second->content.length()))
<< setw(8) << perms
<< time_buf << " \n";
}
return oss.str();
}
string getCurrentDirectory() const {
return " /Puagkhfh- Shell/";
}
// 序列化文件系统
void serialize(BinarySerializer& serializer) const {
ScopedLock lock(fs_mutex);
serializer.writeType(current_user_id);
serializer.writeType(current_group_id);
root->serialize(serializer);
}
// 反序列化文件系统
void deserialize(BinarySerializer& serializer) {
ScopedLock lock(fs_mutex);
current_user_id = serializer.readType<int>();
current_group_id = serializer.readType<int>();
// 重新创建根节点
root = make_shared<DirectoryNode>(" ");
root->deserialize(serializer);
}
// ==================== 进程管理与调度算法 ====================
enum class ProcessState {
READY,
RUNNING,
WAITING,
TERMINATED
};
struct Process {
int pid;
string name;
ProcessState state;
int priority;
int memory_required;
int memory_address;
time_t create_time;
time_t start_time;
time_t end_time;
int cpu_time_used;
mutable std::mutex proc_mutex;
// 显式声明构造函数,避免默认拷贝构造被删除
Process(int id, const string& n, int prio = 0 , int mem = 64 )
: pid(id), name(n), state(ProcessState::READY), priority(prio),
memory_required(mem), memory_address(-1), cpu_time_used(0) {
create_time = time(nullptr)
start_time = 0
end_time = 0
}
// 禁用拷贝构造和赋值(mutex 不能拷贝)
Process(const Process&) = delete
Process& operator =(const Process&) = delete
// 启用移动构造和赋值
Process(Process&& other) noexcept
: pid(other.pid), name(std::move(other.name)), state(other.state),
priority(other.priority), memory_required(other.memory_required),
memory_address(other.memory_address), create_time(other.create_time),
start_time(other.start_time), end_time(other.end_time),
cpu_time_used(other.cpu_time_used) {
// mutex 不能移动,重新初始化
}
Process& operator =(Process&& other) noexcept {
if (this != &other) {
pid = other.pid
name = std::move(other.name)
state = other.state
priority = other.priority
memory_required = other.memory_required
memory_address = other.memory_address
create_time = other.create_time
start_time = other.start_time
end_time = other.end_time
cpu_time_used = other.cpu_time_used
}
return *this
}
void start() {
ScopedLock lock(proc_mutex)
state = ProcessState::RUNNING
start_time = time(nullptr)
}
void terminate() {
ScopedLock lock(proc_mutex)
state = ProcessState::TERMINATED
end_time = time(nullptr)
}
void wait() {
ScopedLock lock(proc_mutex)
if (state == ProcessState::RUNNING) {
state = ProcessState::WAITING
}
}
void ready() {
ScopedLock lock(proc_mutex)
if (state == ProcessState::WAITING) {
state = ProcessState::READY
}
}
int getRuntime() const {
ScopedLock lock(proc_mutex)
if (state == ProcessState::TERMINATED) {
return static_cast<int>(difftime(end_time, start_time))
} else if (state == ProcessState::RUNNING) {
return static_cast<int>(difftime(time(nullptr), start_time))
}
return 0
}
// 序列化进程
void serialize(BinarySerializer& serializer) const {
ScopedLock lock(proc_mutex)
serializer.writeType(pid)
serializer.writeString(name)
serializer.writeType(static_cast<int>(state))
serializer.writeType(priority)
serializer.writeType(memory_required)
serializer.writeType(memory_address)
serializer.writeType(static_cast<uint64_t>(create_time))
serializer.writeType(static_cast<uint64_t>(start_time))
serializer.writeType(static_cast<uint64_t>(end_time))
serializer.writeType(cpu_time_used)
}
// 从二进制数据创建进程(修复拷贝问题)
static shared_ptr<Process> createFromSerialized(BinarySerializer& serializer) {
int pid = serializer.readType<int>()
string name = serializer.readString()
ProcessState state = static_cast<ProcessState>(serializer.readType<int>())
int priority = serializer.readType<int>()
int mem_required = serializer.readType<int>()
int mem_addr = serializer.readType<int>()
time_t create_time = static_cast<time_t>(serializer.readType<uint64_t>())
time_t start_time = static_cast<time_t>(serializer.readType<uint64_t>())
time_t end_time = static_cast<time_t>(serializer.readType<uint64_t>())
int cpu_used = serializer.readType<int>()
// 创建新进程
auto proc = make_shared<Process>(pid, name, priority, mem_required)
proc->state = state
proc->memory_address = mem_addr
proc->create_time = create_time
proc->start_time = start_time
proc->end_time = end_time
proc->cpu_time_used = cpu_used
return proc
}
class ProcessScheduler {
public:
enum class SchedulingAlgorithm {
FCFS, // 先来先服务
PRIORITY, // 优先级调度
SJF, // 短作业优先
ROUND_ROBIN // 时间片轮转
};
private:
SchedulingAlgorithm current_algorithm;
int time_quantum; // 时间片大小(仅用于轮转调度)
mutable std::mutex scheduler_mutex;
public:
ProcessScheduler(SchedulingAlgorithm algo = SchedulingAlgorithm::PRIORITY,
int quantum = 10)
: current_algorithm(algo), time_quantum(quantum) {}
void setAlgorithm(SchedulingAlgorithm algo) {
ScopedLock lock(scheduler_mutex)
current_algorithm = algo
}
int selectNextProcess(const vector<shared_ptr<Process>>& processes) {
ScopedLock lock(scheduler_mutex)
if (processes.empty()) return -1
vector<int> ready_pids
for (const auto& proc : processes) {
ScopedLock proc_lock(proc->proc_mutex)
if (proc->state == ProcessState::READY) {
ready_pids.push_back(proc->pid)
}
}
if (ready_pids.empty()) return -1
switch (current_algorithm) {
case SchedulingAlgorithm::FCFS:
return ready_pids.front()
case SchedulingAlgorithm::PRIORITY: {
int highest_priority = -999
int selected_pid = -1
for (int pid : ready_pids) {
auto proc = findProcess(processes, pid)
if (proc && proc->priority > highest_priority) {
highest_priority = proc->priority
selected_pid = pid
}
}
return selected_pid
}
case SchedulingAlgorithm::SJF: {
int shortest_time = INT_MAX
int selected_pid = -1
for (int pid : ready_pids) {
auto proc = findProcess(processes, pid)
if (proc && proc->cpu_time_used < shortest_time) {
shortest_time = proc->cpu_time_used
selected_pid = pid
}
}
return selected_pid
}
case SchedulingAlgorithm::ROUND_ROBIN: {
static size_t current_index = 0
if (current_index >= ready_pids.size()) current_index = 0
return ready_pids[current_index++]
}
default:
return ready_pids.front()
}
}
// 序列化调度器
void serialize(BinarySerializer& serializer) const {
ScopedLock lock(scheduler_mutex)
serializer.writeType(static_cast<int>(current_algorithm))
serializer.writeType(time_quantum)
}
// 反序列化调度器
void deserialize(BinarySerializer& serializer) {
ScopedLock lock(scheduler_mutex)
current_algorithm = static_cast<SchedulingAlgorithm>(serializer.readType<int>())
time_quantum = serializer.readType<int>()
}
private:
shared_ptr findProcess(const vector<shared_ptr>& processes, int pid) const {
for (const auto& proc : processes) {
if (proc->pid == pid) return proc;
}
return nullptr;
}
};
class ProcessManager {
private:
vector<shared_ptr> processes;
int next_pid;
shared_ptr scheduler;
shared_ptr memory_manager;
mutable std::mutex pm_mutex;
public:
ProcessManager(shared_ptr mem_mgr)
: next_pid(1), memory_manager(mem_mgr) {
scheduler = make_shared();
}
int createProcess (const string& name, int priority = 0 , int memory = 64 ) {
ScopedLock lock (pm_mutex) ;
int new_pid = next_pid++;
auto proc = make_shared <Process >(new_pid, name, priority, memory);
int mem_addr = memory_manager->allocateMemory (memory, new_pid, name);
if (mem_addr == -1 ) {
return -1 ;
}
proc->memory_address = mem_addr;
processes.push_back (proc);
return new_pid;
}
bool terminateProcess (int pid) {
ScopedLock lock (pm_mutex) ;
for (auto it = processes.begin (); it != processes.end (); ++it) {
if ((*it)->pid == pid) {
if ((*it)->memory_address != -1 ) {
memory_manager->freeMemory ((*it)->memory_address);
}
(*it)->terminate ();
return true ;
}
}
return false ;
}
vector<shared_ptr<Process >> listProcesses () const {
ScopedLock lock (pm_mutex) ;
return processes;
}
bool setPriority (int pid, int new_priority) {
ScopedLock lock (pm_mutex) ;
for (auto & proc : processes) {
if (proc->pid == pid) {
ScopedLock proc_lock (proc->proc_mutex) ;
proc->priority = new_priority;
return true ;
}
}
return false ;
}
bool scheduleProcess () {
ScopedLock lock (pm_mutex) ;
int next_pid = scheduler->selectNextProcess (processes);
if (next_pid == -1 ) return false ;
for (auto & proc : processes) {
ScopedLock proc_lock (proc->proc_mutex) ;
if (proc->pid == next_pid && proc->state == ProcessState::READY) {
for (auto & p : processes) {
if (p->state == ProcessState::RUNNING) {
p->state = ProcessState::READY;
}
}
proc->start ();
proc->cpu_time_used++;
return true ;
}
}
return false ;
}
void setSchedulingAlgorithm (ProcessScheduler::SchedulingAlgorithm algo) {
scheduler->setAlgorithm (algo);
}
string getProcessInfo (int pid) const {
ScopedLock lock (pm_mutex) ;
for (const auto & proc : processes) {
if (proc->pid == pid) {
ScopedLock proc_lock (proc->proc_mutex) ;
ostringstream oss;
oss << "进程信息:\n"
<< string (30 , '=' ) << "\n"
<< "PID: " << proc->pid << "\n"
<< "名称:" << proc->name << "\n"
<< "状态:" ;
switch (proc->state) {
case ProcessState::READY: oss << "就绪" ; break ;
case ProcessState::RUNNING: oss << "运行中" ; break ;
case ProcessState::WAITING: oss << "等待" ; break ;
case ProcessState::TERMINATED: oss << "已终止" ; break ;
}
oss << "\n优先级:" << proc->priority << "\n"
<< "内存:" << proc->memory_required << " KB (地址:"
<< (proc->memory_address != -1 ? to_string (proc->memory_address) : "未分配" )
<< ")\n"
<< "运行时间:" << proc->getRuntime () << "秒\n"
<< "CPU 时间:" << proc->cpu_time_used << "单位\n" ;
return oss.str ();
}
}
return "进程未找到" ;
}
void serialize (BinarySerializer& serializer) const {
ScopedLock lock (pm_mutex) ;
serializer.writeType (next_pid);
scheduler->serialize (serializer);
serializer.writeType (static_cast <uint32_t >(processes.size ()));
for (const auto & proc : processes) {
proc->serialize (serializer);
}
}
void deserialize (BinarySerializer& serializer) {
ScopedLock lock (pm_mutex) ;
processes.clear ();
next_pid = serializer.readType <int >();
scheduler->deserialize (serializer);
uint32_t proc_count = serializer.readType <uint32_t >();
for (uint32_t i = 0 ; i < proc_count; i++) {
auto proc = Process ::createFromSerialized (serializer);
processes.push_back (proc);
}
}
// ==================== 内核(系统核心模块) ====================
class Kernel {
public:
FileSystem fs;
shared_ptr pm;
shared_ptr mm;
// 自动保存相关配置
bool auto_save_enabled
int auto_save_interval
string auto_save_filename
mutable std::mutex auto_save_mutex
std::condition_variable auto_save_cv
std::thread auto_save_thread
bool auto_save_running
enum class SyscallType {
PRINT,
READ_FILE,
WRITE_FILE,
CREATE_FILE,
DELETE_FILE,
LIST_FILES,
CREATE_DIR,
CHANGE_DIR,
CHANGE_PERMS,
EXEC_PROGRAM,
GET_PROCESSES,
TERMINATE_PROCESS,
SET_PRIORITY,
SET_SCHEDULER,
GET_TIME,
RANDOM_NUMBER,
MEMORY_STATUS,
PROCESS_INFO,
SAVE_SYSTEM, // 新增:保存系统状态
LOAD_SYSTEM, // 新增:加载系统状态
AUTO_SAVE, // 新增:配置自动保存
SHOW_AUTO_SAVE // 新增:显示自动保存状态
}
Kernel() {
mm = make_shared<MemoryManager>(4096 )
pm = make_shared<ProcessManager>(mm)
fs.setCurrentUser(1000, 100)
// 初始化自动保存配置
auto_save_enabled = true
auto_save_interval = 30
auto_save_filename = "auto_save.io"
auto_save_running = true
// 启动自动保存线程
auto_save_thread = std::thread(&Kernel::autoSaveLoop, this)
// 初始化目录结构
fs.createDirectory("/home")
fs.createDirectory("/home/user")
fs.createDirectory("/etc")
fs.createDirectory("/tmp")
}
// 析构函数:确保线程正确退出
~Kernel() {
{
std::lock_guard<std::mutex> lock(auto_save_mutex)
auto_save_running = false
auto_save_cv.notify_one()
}
if (auto_save_thread.joinable()) {
auto_save_thread.join()
}
}
// 自动保存循环
void autoSaveLoop() {
std::unique_lock<std::mutex> lock(auto_save_mutex)
while (auto_save_running) {
// 等待指定时间或被唤醒
auto_save_cv.wait_for(lock, std::chrono::seconds(auto_save_interval),
[this] () { return !auto_save_running
// 如果线程需要退出,直接返回
if (!auto_save_running) break
// 如果启用了自动保存,执行保存
if (auto_save_enabled) {
try {
string output
saveSystemState(auto_save_filename, output)
// 打印自动保存信息(可选)
std::cout << "[自动保存] 系统状态已保存到:" << auto_save_filename << "\n"
} catch (const std::exception& e) {
// 自动保存失败时的错误处理
std::cerr << "[自动保存] 保存失败:" << e.what() << "\n"
}
}
}
}
// 保存系统状态的内部方法
bool saveSystemState(const string& filename, string& output) {
try {
BinarySerializer serializer
// 写入文件头标识
serializer.writeString("SIM_OS_IMAGE")
serializer.writeType(static_cast<uint32_t>(1))
// 序列化各模块
fs.serialize(serializer)
mm->serialize(serializer)
pm->serialize(serializer)
// 写入文件
ofstream file(filename, ios::binary | ios::trunc)
if (!file.is_open()) {
output = "错误:无法创建文件 '" + filename + "'"
return false
}
vector<char> data = serializer.getData()
file.write(data.data(), data.size())
file.close()
output = "系统状态已保存到:" + filename
return true
} catch (const exception& e) {
output = "保存失败:" + string(e.what())
return false
}
}
// 加载系统状态的内部方法
bool loadSystemState(const string& filename, string& output) {
try {
// 读取文件
ifstream file(filename, ios::binary)
if (!file.is_open()) {
output = "错误:无法打开文件 '" + filename + "'"
return false
}
// 获取文件大小
file.seekg(0, ios::end)
size_t file_size = file.tellg()
file.seekg(0, ios::beg)
// 读取所有数据
vector<char> data(file_size)
file.read(data.data(), file_size)
file.close()
BinarySerializer serializer(data)
// 验证文件头
string header = serializer.readString()
uint32_t version = serializer.readType<uint32_t>()
if (header != "SIM_OS_IMAGE" || version != 1) {
output = "错误:无效的系统镜像文件"
return false
}
// 反序列化各模块
fs.deserialize(serializer)
mm->deserialize(serializer)
pm->deserialize(serializer)
output = "系统状态已从:" + filename + " 加载完成"
return true
} catch (const exception& e) {
output = "加载失败:" + string(e.what())
return false
}
}
void syscall(SyscallType type, const vector<string>& args, string& output) {
switch (type) {
case SyscallType::PRINT:
if (!args.empty()) output = args[0 ]
break
case SyscallType::READ_FILE:
if (!args.empty()) {
output = fs.readFile(args[0 ])
}
break
case SyscallType::WRITE_FILE:
if (args.size() >= 2) {
if (fs.writeFile(args[0] , args[1] )) {
output = "成功写入文件 '" + args[0 ] + "'"
} else {
output = "错误:无法写入文件 '" + args[0 ] + "'"
}
}
break
case SyscallType::CREATE_FILE:
if (!args.empty()) {
if (fs.createFile(args[0] )) {
output = "文件 '" + args[0 ] + "' 已创建"
} else {
output = "错误:无法创建文件 '" + args[0 ] + "'"
}
}
break
case SyscallType::DELETE_FILE:
if (!args.empty()) {
if (fs.deleteNode(args[0] )) {
output = "文件/目录 '" + args[0 ] + "' 已删除"
} else {
output = "错误:无法删除 '" + args[0 ] + "'"
}
}
break
case SyscallType::LIST_FILES:
if (args.empty()) {
output = fs.listDirectory()
} else {
output = fs.listDirectory(args[1 ])
}
break
case SyscallType::CREATE_DIR:
if (!args.empty()) {
if (fs.createDirectory(args[0] )) {
output = "目录 '" + args[0 ] + "' 已创建"
} else {
output = "错误:无法创建目录 '" + args[0 ] + "'"
}
}
break
case SyscallType::CHANGE_DIR:
output = "目录已切换到:" + (args.empty() ? "/" : args[0 ])
break
case SyscallType::CHANGE_PERMS:
if (args.size() >= 2) {
try {
int perms = stoi(args[1 ])
if (fs.changePermissions(args[0] , perms)) {
output = "权限已修改"
} else {
output = "错误:无法修改权限"
}
} catch (...) {
output = "错误:无效的权限格式,使用 3 位数字 (如 755)"
}
}
break
case SyscallType::EXEC_PROGRAM:
output = "程序执行功能尚未实现"
break
case SyscallType::GET_PROCESSES: {
auto procs = pm->listProcesses()
if (procs.empty()) {
output = "没有正在运行的进程"
} else {
ostringstream oss
oss << "进程列表:\n"
<< string(60, '-') << "\n"
<< left << setw(5) << "PID"
<< setw(15) << "名称"
<< setw(10) << "状态"
<< setw(8) << "优先级"
<< setw(10) << "内存 (KB)"
<< "CPU 时间\n"
<< string(60, '-') << "\n"
for (const auto& p : procs) {
ScopedLock lock(p->proc_mutex)
string state_str
switch (p->state) {
case ProcessState::READY: state_str = "就绪"
case ProcessState::RUNNING: state_str = "运行"
case ProcessState::WAITING: state_str = "等待"
case ProcessState::TERMINATED: state_str = "终止"
}
oss << left << setw(5) << p->pid
<< setw(15) << p->name
<< setw(10) << state_str
<< setw(8) << p->priority
<< setw(10) << p->memory_required
<< p->cpu_time_used << "\n"
}
output = oss.str()
}
break
}
case SyscallType::TERMINATE_PROCESS:
if (!args.empty()) {
try {
int pid = stoi(args[0 ])
if (pm->terminateProcess(pid)) {
output = "进程 " + to_string(pid) + " 已终止"
} else {
output = "错误:未找到进程 " + to_string(pid)
}
} catch (...) {
output = "错误:无效的 PID '" + args[0 ] + "'"
}
}
break
case SyscallType::SET_PRIORITY:
if (args.size() >= 2) {
try {
int pid = stoi(args[0 ])
int prio = stoi(args[1 ])
if (pm->setPriority(pid, prio)) {
output = "进程 " + to_string(pid) + " 优先级已设置为 " + to_string(prio)
} else {
output = "错误:未找到进程 " + to_string(pid)
}
} catch (...) {
output = "错误:无效的 PID 或优先级"
}
}
break
case SyscallType::SET_SCHEDULER:
if (!args.empty()) {
if (args[0] == "fcfs") {
pm->setSchedulingAlgorithm(ProcessScheduler::SchedulingAlgorithm::FCFS)
output = "调度算法已切换为 先来先服务 (FCFS)"
} else if (args[0] == "priority") {
pm->setSchedulingAlgorithm(ProcessScheduler::SchedulingAlgorithm::PRIORITY)
output = "调度算法已切换为 优先级调度"
} else if (args[0] == "sjf") {
pm->setSchedulingAlgorithm(ProcessScheduler::SchedulingAlgorithm::SJF)
output = "调度算法已切换为 短作业优先 (SJF)"
} else if (args[0] == "rr") {
pm->setSchedulingAlgorithm(ProcessScheduler::SchedulingAlgorithm::ROUND_ROBIN)
output = "调度算法已切换为 时间片轮转 (Round Robin)"
} else {
output = "错误:未知的调度算法,可用:fcfs, priority, sjf, rr"
}
}
break
case SyscallType::GET_TIME: {
time_t t = time(0 )
output = ctime(&t)
if (!output.empty() && output.back() == '\n') output.pop_back()
break
}
case SyscallType::RANDOM_NUMBER: {
int max_val = 100
if (!args.empty()) {
try {
max_val = stoi(args[0 ])
} catch (...) {
output = "错误:最大数值必须为整数"
return
}
}
output = to_string(rand() % max_val)
break
}
case SyscallType::MEMORY_STATUS: {
auto blocks = mm->getMemoryStatus()
ostringstream oss
oss << "内存状态 (总内存:" << mm->getTotalUsedMemory() + mm->getTotalFreeMemory()
<< " KB, 已用:" << mm->getTotalUsedMemory()
<< " KB, 空闲:" << mm->getTotalFreeMemory() << " KB)\n"
<< string(70, '-') << "\n"
<< left << setw(10) << "起始地址"
<< setw(10) << "大小 (KB)"
<< setw(15) << "状态"
<< setw(10) << "所属 PID"
<< "描述\n"
<< string(70, '-') << "\n"
for (const auto& block : blocks) {
oss << left << setw(10) << block.start_address
<< setw(10) << block.size
<< setw(15) << (block.allocated ? "已分配" : "空闲")
<< setw(10) << (block.allocated ? to_string(block.owner_pid) : "-")
<< block.description << "\n"
}
output = oss.str()
break
}
case SyscallType::PROCESS_INFO:
if (!args.empty()) {
try {
int pid = stoi(args[0 ])
output = pm->getProcessInfo(pid)
} catch (...) {
output = "错误:无效的 PID"
}
}
break
// 保存系统状态
case SyscallType::SAVE_SYSTEM: {
if (args.empty()) {
output = "错误:请指定保存文件名(如 save system.io)"
break
}
string filename = args[0 ]
// 确保文件扩展名是 .io
if (filename.length() < 4 || filename.substr(filename.length() - 3) != ".io") {
filename += ".io"
}
saveSystemState(filename, output)
break
}
// 加载系统状态
case SyscallType::LOAD_SYSTEM: {
if (args.empty()) {
output = "错误:请指定加载文件名(如 load system.io)"
break
}
string filename = args[0 ]
// 确保文件扩展名是 .io
if (filename.length() < 4 || filename.substr(filename.length() - 3) != ".io") {
filename += ".io"
}
loadSystemState(filename, output)
break
}
// 配置自动保存
case SyscallType::AUTO_SAVE: {
if (args.empty()) {
output = "用法:autosave [on/off] [间隔秒数] [文件名]\n"
"示例:\n"
" autosave on - 开启自动保存\n"
" autosave off - 关闭自动保存\n"
" autosave interval 60 - 设置保存间隔为 60 秒\n"
" autosave file mysave.io - 设置保存文件名为 mysave.io\n"
break
}
std::lock_guard<std::mutex> lock(auto_save_mutex)
if (args[0] == "on") {
auto_save_enabled = true
output = "自动保存已开启"
auto_save_cv.notify_one()
} else if (args[0] == "off") {
auto_save_enabled = false
output = "自动保存已关闭"
} else if (args[0] == "interval" && args.size() >= 2) {
try {
int interval = stoi(args[1 ])
if (interval < 5) {
output = "错误:保存间隔不能小于 5 秒"
} else {
auto_save_interval = interval
output = "自动保存间隔已设置为 " + to_string(interval) + " 秒"
auto_save_cv.notify_one()
}
} catch (...) {
output = "错误:无效的时间间隔值"
}
} else if (args[0] == "file" && args.size() >= 2) {
string filename = args[1 ]
if (filename.length() < 4 || filename.substr(filename.length() - 3) != ".io") {
filename += ".io"
}
auto_save_filename = filename
output = "自动保存文件名已设置为:" + filename
} else {
output = "无效的自动保存命令,输入 'autosave' 查看帮助"
}
break
}
// 显示自动保存状态
case SyscallType::SHOW_AUTO_SAVE: {
std::lock_guard<std::mutex> lock(auto_save_mutex)
ostringstream oss
oss << "自动保存状态:\n"
<< string(30, '-') << "\n"
<< "状态:" << (auto_save_enabled ? "已开启" : "已关闭") << "\n"
<< "保存间隔:" << auto_save_interval << " 秒\n"
<< "保存文件:" << auto_save_filename << "\n"
output = oss.str()
break
}
default:
output = "未知系统调用"
break
}
}
// ==================== 用户空间程序(应用程序) ====================
class UserProgram {
protected:
Kernel* kernel_;
int pid_;
public:
// 修复:移除错误的自委托构造函数
UserProgram(Kernel* k, int pid = -1) : kernel_(k), pid_(pid) {}
virtual ~UserProgram() = default;
virtual void run() = 0;
};
// 计算器程序
class Calculator : public UserProgram {
public:
Calculator(Kernel* k, int pid = -1) : UserProgram(k, pid) {}
void run () override {
cout << "简易计算器(输入 '退出' 结束)\n" ;
string expr;
while (true ) {
cout << "计算> " ;
getline (cin, expr);
if (expr == "退出" || expr == "quit" ) break ;
try {
size_t pos;
double num1 = stod (expr, &pos);
while (pos < expr.size () && isspace (expr[pos])) pos++;
if (pos >= expr.size ()) throw invalid_argument ("缺少运算符" );
char op = expr[pos++];
while (pos < expr.size () && isspace (expr[pos])) pos++;
if (pos >= expr.size ()) throw invalid_argument ("缺少第二个数字" );
double num2 = stod (expr.substr (pos), nullptr );
double result = 0 ;
switch (op) {
case '+' : result = num1 + num2; break ;
case '-' : result = num1 - num2; break ;
case '*' : result = num1 * num2; break ;
case '/' :
if (num2 == 0 ) throw runtime_error ("除数不能为零" );
result = num1 / num2;
break ;
default : throw invalid_argument ("无效运算符,支持:+, -, *, /" );
}
cout << "结果:" << result << "\n" ;
} catch (const exception& e) {
cout << "错误:" << e.what () << "\n" ;
}
}
cout << "计算器程序已退出\n" ;
}
// 文本编辑器程序
class TextEditor : public UserProgram {
public:
TextEditor(Kernel* k, int pid = -1) : UserProgram(k, pid) {}
void run () override {
cout << "简易文本编辑器(输入 ':q' 保存退出,':q!' 不保存退出)\n" ;
cout << "请输入文件名:" ;
string filename;
getline(cin , filename);
string content;
cout << "开始编辑(每行输入后按回车,结束输入请用 ':q' 或 ':q!'):\n" ;
while (true ) {
string line;
getline(cin , line);
if (line == ":q" ) {
string output;
kernel_->syscall(Kernel::SyscallType::WRITE_FILE, {filename, content}, output);
cout << output << "\n" ;
break ;
} else if (line == ":q!" ) {
cout << "已放弃保存\n" ;
break ;
} else {
content += line + "\n" ;
}
}
cout << "文本编辑器已退出\n" ;
}
// 命令行解释器
class Shell {
private:
Kernel& kernel;
bool running;
vector <string > splitCommand (const string & cmd) {
vector <string > args;
stringstream ss (cmd) ;
string arg;
while (ss >> arg) {
args.push_back(arg);
}
return args;
}
public:
Shell(Kernel& k) : kernel(k), running(true) {}
void run() {
cout << "Puagkhfh- Shell(5.0)\n"
cout << "Puagkhfh- Shell - 保留所有权利\n"
cout << "输入 'help' 查看命令列表,'exit' 退出系统\n"
cout << "系统已启用自动保存,输入 'autosave' 查看自动保存配置\n"
while (running) {
cout << kernel.fs.getCurrentDirectory() << "> "
string cmd
getline(cin, cmd)
vector<string> args = splitCommand(cmd)
if (args.empty()) continue
if (args[0] == "exit") {
running = false
cout << "系统已关闭\n"
} else if (args[0] == "help") {
printHelp()
} else if (args[0] == "ls") {
string path = args.size() > 1 ? args[1 ] : ""
string output
kernel.syscall(Kernel::SyscallType::LIST_FILES, {path}, output)
cout << output << "\n"
} else if (args[0] == "mkdir") {
if (args.size() < 2) {
cout << "用法:mkdir <目录路径>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::CREATE_DIR, {args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "touch") {
if (args.size() < 2) {
cout << "用法:touch <文件路径>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::CREATE_FILE, {args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "rm") {
if (args.size() < 2) {
cout << "用法:rm <文件/目录路径>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::DELETE_FILE, {args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "cat") {
if (args.size() < 2) {
cout << "用法:cat <文件路径>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::READ_FILE, {args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "echo") {
if (args.size() < 3 || args[1] != ">") {
cout << "用法:echo <内容> > <文件路径>\n"
} else {
string content
for (size_t i = 2
content += args[i] + " "
}
if (args.size() > 2) {
content += args.back()
}
string output
kernel.syscall(Kernel::SyscallType::WRITE_FILE, {args.back(), content}, output)
cout << output << "\n"
}
} else if (args[0] == "chmod") {
if (args.size() < 3) {
cout << "用法:chmod <权限> <文件/目录路径>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::CHANGE_PERMS, {args[2] , args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "ps") {
string output
kernel.syscall(Kernel::SyscallType::GET_PROCESSES, {}, output)
cout << output << "\n"
} else if (args[0] == "kill") {
if (args.size() < 2) {
cout << "用法:kill <PID>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::TERMINATE_PROCESS, {args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "nice") {
if (args.size() < 3) {
cout << "用法:nice <PID> <优先级>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::SET_PRIORITY, {args[1] , args[2] }, output)
cout << output << "\n"
}
} else if (args[0] == "sched") {
if (args.size() < 2) {
cout << "用法:sched <算法> (fcfs/priority/sjf/rr)\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::SET_SCHEDULER, {args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "time") {
string output
kernel.syscall(Kernel::SyscallType::GET_TIME, {}, output)
cout << output << "\n"
} else if (args[0] == "memory") {
string output
kernel.syscall(Kernel::SyscallType::MEMORY_STATUS, {}, output)
cout << output << "\n"
} else if (args[0] == "proc") {
if (args.size() < 2) {
cout << "用法:proc <PID>\n"
} else {
string output
kernel.syscall(Kernel::SyscallType::PROCESS_INFO, {args[1] }, output)
cout << output << "\n"
}
} else if (args[0] == "calc") {
int pid = kernel.pm->createProcess("calculator" , 1 , 32 )
if (pid == -1 ) {
cout << "创建计算器进程失败(内存不足)\n"
} else {
cout << "计算器进程已启动 (PID: " << pid << ")\n"
Calculator calc(&kernel, pid)
calc.run()
}
} else if (args[0] == "edit") {
int pid = kernel.pm->createProcess("text_editor" , 1 , 64 )
if (pid == -1 ) {
cout << "创建编辑器进程失败(内存不足)\n"
} else {
cout << "文本编辑器已启动 (PID: " << pid << ")\n"
TextEditor editor(&kernel, pid)
editor.run()
}
} else if (args[0] == "save") {
string output
vector<string> save_args
if (args.size() > 1) {
save_args.push_back(args[1] )
}
kernel.syscall(Kernel::SyscallType::SAVE_SYSTEM, save_args, output)
cout << output << "\n"
} else if (args[0] == "load") {
string output
vector<string> load_args
if (args.size() > 1) {
load_args.push_back(args[1] )
}
kernel.syscall(Kernel::SyscallType::LOAD_SYSTEM, load_args, output)
cout << output << "\n"
}
// 新增:自动保存相关命令
else if (args[0] == "autosave") {
string output
vector<string> autosave_args
for (size_t i = 1
autosave_args.push_back(args[i] )
}
kernel.syscall(Kernel::SyscallType::AUTO_SAVE, autosave_args, output)
cout << output << "\n"
}
else {
cout << "未知命令:" << args[0] << ",输入 'help' 查看帮助\n"
}
// 每次命令执行后进行进程调度
kernel.pm->scheduleProcess()
}
}
void printHelp() {
cout << "支持的命令:\n"
cout << " exit - 退出系统\n"
cout << " help - 显示帮助信息\n"
cout << " ls [路径] - 列出目录内容\n"
cout << " mkdir <路径> - 创建目录\n"
cout << " touch <路径> - 创建文件\n"
cout << " rm <路径> - 删除文件/目录\n"
cout << " cat <文件> - 查看文件内容\n"
cout << " echo <内容> > <文件> - 写入文件\n"
cout << " chmod <权限> <路径> - 修改权限\n"
cout << " ps - 查看进程列表\n"
cout << " kill <PID> - 终止进程\n"
cout << " nice <PID> <优先级> - 修改进程优先级\n"
cout << " sched <算法> - 设置调度算法 (fcfs/priority/sjf/rr)\n"
cout << " time - 显示当前时间\n"
cout << " memory - 查看内存状态\n"
cout << " proc <PID> - 查看进程详细信息\n"
cout << " calc - 启动计算器\n"
cout << " edit - 启动文本编辑器\n"
cout << " save <文件名> - 保存系统状态到.io 文件\n"
cout << " load <文件名> - 从.io 文件加载系统状态\n"
cout << " autosave - 查看自动保存配置\n\n"
cout << " Puagkhfh- Shell - 保留所有权利\n"
}
// 主函数
int main() {
srand(time(nullptr));
Kernel kernel;
Shell shell(kernel);
shell.run();
return 0;
}