Skip to content

Mo7ammedd/SimuKernel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SimuKernel - Operating System Simulator

C# project that simulates fundamental operating system concepts including CPU scheduling algorithms, memory paging, and a mini kernel with process management. Built with .NET 8


Read the full article: https://modev.me/blog/simukernel-operating-system-concepts

The article provides in-depth explanations of:

  • CPU scheduling algorithms and their real-world applications
  • Memory management and paging techniques
  • Process lifecycle and kernel operations
  • Performance metrics and analysis

Features

1. CPU Thread Scheduler Simulator

Implements multiple scheduling algorithms with real-time visualization:

  • Round Robin (RR): Preemptive scheduling with configurable time quantum
  • Priority Scheduling: Both preemptive and non-preemptive modes
  • Multilevel Feedback Queue (MLFQ): Multiple priority queues with aging mechanism

Each scheduler provides:

  • Process attributes: PID, Burst Time, Priority, Arrival Time
  • Real-time console visualization of scheduling order
  • Detailed metrics: Waiting Time, Turnaround Time, Response Time, CPU Utilization
  • Gantt charts and execution timelines
  • Step-by-step simulation logs

2. Memory Paging Simulation

Virtual memory manager with page replacement algorithms:

  • FIFO (First-In-First-Out): Simple queue-based replacement
  • LRU (Least Recently Used): Replaces least recently accessed pages
  • Optimal: Theoretical optimal replacement (future knowledge)

Features:

  • Configurable number of frames and reference strings
  • Step-by-step visualization of page faults and hits
  • Frame table status display
  • Statistics: Page Fault Rate, Hit Rate, Total References
  • Dynamic algorithm switching via CLI menu

3. Mini Kernel / Process Simulator

In-memory kernel simulation with command-line interface:

  • Boot Sequence: Simulated kernel boot with initialization messages

  • Command Shell: Interactive CLI with commands:

    • help - Display available commands
    • meminfo - Show memory allocation and usage
    • tasks - List all running processes
    • create <name> <size> - Create new process with memory allocation
    • kill <pid> - Terminate a process and free memory
    • run - Execute round-robin scheduler simulation
    • shutdown - Exit the kernel
  • Memory Management: First-fit allocation strategy with visual memory map

  • Process Scheduling: In-memory round-robin scheduler

Architecture

/SimuKernel
├── config.json                 # Configuration file
├── SimuKernel.csproj          # Project file
├── Program.cs                  # Entry point
├── /Core                       # Core OS logic
│   ├── IScheduler.cs          # Scheduler interface
│   ├── Process.cs             # Process model
│   ├── ScheduleResult.cs      # Result data structures
│   ├── /Schedulers
│   │   ├── RoundRobinScheduler.cs
│   │   ├── PriorityScheduler.cs
│   │   └── MLFQScheduler.cs
│   └── /Memory
│       ├── IMemoryManager.cs
│       ├── MemoryModels.cs
│       ├── FIFOMemoryManager.cs
│       ├── LRUMemoryManager.cs
│       └── OptimalMemoryManager.cs
├── /CLI                        # Console interface
│   └── MenuSystem.cs
├── /KernelSim                 # Mini kernel
│   └── MiniKernel.cs
└── /Utils                      # Utilities
    ├── Configuration.cs
    ├── Logger.cs
    └── Visualizer.cs

Installation & Setup on Fedora Linux

Prerequisites

  1. Install .NET 8 SDK:
sudo dnf install dotnet-sdk-8.0
  1. Verify Installation:
dotnet --version

Building the Project

  1. Clone or navigate to the project directory:
cd /home/SimuKernel
  1. Restore dependencies:
dotnet restore
  1. Build the project:
dotnet build
  1. Run the application:
dotnet run

Usage Guide

Main Menu

When you start SimuKernel, you'll see an interactive menu:

=== Main Menu ===

1. CPU Scheduling Simulator
2. Memory Paging Simulator
3. View Configuration
4. Toggle Logging
5. Exit

CPU Scheduling Simulator

  1. Select option 1 from the main menu

  2. Choose a scheduling algorithm:

    • Round Robin
    • Priority Scheduling (Preemptive/Non-Preemptive)
    • Multilevel Feedback Queue
    • Compare All Algorithms
  3. Input process data:

    • Use sample data for quick testing
    • Enter custom processes with Burst Time, Priority, and Arrival Time
  4. View results:

    • Execution timeline with ready queue status
    • Process completion details
    • Statistics (average waiting time, turnaround time, CPU utilization)
    • Gantt charts

Memory Paging Simulator

  1. Select option 2 from the main menu

  2. Choose a page replacement algorithm:

    • FIFO
    • LRU
    • Optimal
    • Compare All Algorithms
  3. Input reference string:

    • Use sample data (default: 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1)
    • Enter custom reference string (space-separated page numbers)
    • Specify number of frames
  4. View results:

    • Step-by-step page access with fault/hit indication
    • Frame state visualization
    • Statistics (page faults, hits, fault rate, hit rate)

Configuration

Edit config.json to customize behavior:

{
  "Scheduler": {
    "RoundRobin": {
      "TimeQuantum": 4
    },
    "MLFQ": {
      "NumberOfQueues": 3,
      "TimeQuantums": [2, 4, 8],
      "AgingThreshold": 10
    }
  },
  "Memory": {
    "NumberOfFrames": 4,
    "PageSize": 4096
  },
  "Logging": {
    "Enabled": true,
    "LogFilePath": "simulation.log"
  }
}

Mini Kernel Access

The mini kernel is implemented in the codebase but not directly accessible from the main menu. To use it, modify Program.cs:

// In Main method, replace menu.ShowMainMenu() with:
var kernel = new KernelSim.MiniKernel(1024);
kernel.Boot();

Then rebuild and run:

dotnet build
dotnet run

Educational Concepts

CPU Scheduling

Round Robin (RR)

  • Preemptive time-sharing algorithm
  • Each process gets equal CPU time (time quantum)
  • Prevents starvation, ensures fairness
  • Context switching overhead increases with small quantum
  • Used in: Modern multi-user operating systems (Linux, Windows)

Priority Scheduling

  • Processes assigned priority levels (lower number = higher priority)
  • Preemptive mode: Running process can be interrupted by higher priority
  • Non-preemptive: Current process runs to completion
  • Risk of starvation for low-priority processes
  • Used in: Real-time systems, I/O-bound process handling

Multilevel Feedback Queue (MLFQ)

  • Multiple queues with different priority levels
  • New processes start in highest priority queue
  • Processes move down queues if they use full time quantum
  • Aging mechanism prevents starvation (moves old processes up)
  • Balances interactive and CPU-bound processes
  • Used in: Modern Unix/Linux systems, Windows NT

Memory Management

Virtual Memory & Paging

  • Divides memory into fixed-size pages
  • Allows processes to use more memory than physically available
  • Page table maps virtual addresses to physical frames
  • Page faults occur when accessing non-resident pages

FIFO Page Replacement

  • Simplest algorithm: removes oldest page
  • Can suffer from Belady's anomaly (more frames → more faults)
  • Low overhead, easy to implement
  • Used in: Simple embedded systems

LRU (Least Recently Used)

  • Replaces page not used for longest time
  • Approximates optimal based on past behavior
  • Higher overhead (tracking access times)
  • Used in: Modern operating systems with hardware support

Optimal Page Replacement

  • Theoretical best: replaces page not needed for longest future time
  • Requires future knowledge (impossible in practice)
  • Used as benchmark to compare real algorithms

Kernel Basics

Boot Sequence

  • BIOS/UEFI loads bootloader
  • Bootloader loads kernel into memory
  • Kernel initializes hardware and drivers
  • Mounts root filesystem
  • Starts init/systemd process

Process Management

  • Process creation (fork/exec)
  • Context switching between processes
  • Process states: Ready, Running, Waiting, Completed
  • Scheduler decides which process runs next

Memory Allocation

  • First-fit: Allocate first block large enough
  • Best-fit: Allocate smallest sufficient block
  • Worst-fit: Allocate largest available block
  • Fragmentation: Internal (wasted within blocks) vs External (between blocks)

Extending the Project

Adding New Scheduling Algorithms

  1. Create a new class implementing IScheduler:
public class SJFScheduler : IScheduler
{
    public string Name => "Shortest Job First";
    
    public ScheduleResult Schedule(List<Process> processes)
    {
        // Implementation
    }
    
    public void PrintResults(ScheduleResult result)
    {
        // Visualization
    }
}
  1. Add to menu in MenuSystem.cs

Adding New Page Replacement Algorithms

  1. Create a new class implementing IMemoryManager:
public class ClockMemoryManager : IMemoryManager
{
    public string Name => "Clock (Second Chance)";
    
    public MemorySimulationResult Simulate(int[] referenceString, int numberOfFrames)
    {
        // Implementation
    }
}
  1. Add to memory menu in MenuSystem.cs

Customizing Visualization

Modify Visualizer.cs to add new chart types or formatting options.

Advanced Features

  • Multi-core scheduling: Simulate multiple CPUs
  • Demand paging: Simulate page loading from disk
  • Disk scheduling: Add FCFS, SCAN, C-SCAN algorithms
  • File system simulation: Implement inode structure
  • Network stack: Basic TCP/IP simulation

Logging

All simulation results are logged to simulation.log when logging is enabled:

cat simulation.log

Log entries include:

  • Timestamp
  • Algorithm name
  • Process/page access details
  • Summary statistics

Performance Considerations

  • Schedulers handle up to thousands of processes efficiently
  • Memory simulations optimized for large reference strings
  • Logging can be disabled for faster execution
  • ASCII visualizations scale with terminal width

Troubleshooting

Issue: dotnet: command not found

  • Solution: Install .NET SDK: sudo dnf install dotnet-sdk-8.0

Issue: Build errors about missing dependencies

  • Solution: Run dotnet restore

Issue: Config file not found

  • Solution: Ensure config.json is in the project root, or it will be auto-created

Issue: Log file permission denied

  • Solution: Check write permissions: chmod +w simulation.log

License

MIT License - See LICENSE file for details.

Copyright (c) 2025 Mohamed Mostafa (mo7ammedd)

Contributing

To contribute:

  1. Fork the repository
  2. Create a feature branch
  3. Implement your changes with proper documentation
  4. Submit a pull request

Additional Resources

Author

Mohamed Mostafa (@mo7ammedd)

About

OS simulator exploring scheduling, memory management, and kernel concepts.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages