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
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
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
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 commandsmeminfo- Show memory allocation and usagetasks- List all running processescreate <name> <size>- Create new process with memory allocationkill <pid>- Terminate a process and free memoryrun- Execute round-robin scheduler simulationshutdown- Exit the kernel
-
Memory Management: First-fit allocation strategy with visual memory map
-
Process Scheduling: In-memory round-robin scheduler
/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
- Install .NET 8 SDK:
sudo dnf install dotnet-sdk-8.0- Verify Installation:
dotnet --version- Clone or navigate to the project directory:
cd /home/SimuKernel- Restore dependencies:
dotnet restore- Build the project:
dotnet build- Run the application:
dotnet runWhen 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
-
Select option
1from the main menu -
Choose a scheduling algorithm:
- Round Robin
- Priority Scheduling (Preemptive/Non-Preemptive)
- Multilevel Feedback Queue
- Compare All Algorithms
-
Input process data:
- Use sample data for quick testing
- Enter custom processes with Burst Time, Priority, and Arrival Time
-
View results:
- Execution timeline with ready queue status
- Process completion details
- Statistics (average waiting time, turnaround time, CPU utilization)
- Gantt charts
-
Select option
2from the main menu -
Choose a page replacement algorithm:
- FIFO
- LRU
- Optimal
- Compare All Algorithms
-
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
- Use sample data (default:
-
View results:
- Step-by-step page access with fault/hit indication
- Frame state visualization
- Statistics (page faults, hits, fault rate, hit rate)
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"
}
}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 runRound 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
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
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)
- 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
}
}- Add to menu in
MenuSystem.cs
- Create a new class implementing
IMemoryManager:
public class ClockMemoryManager : IMemoryManager
{
public string Name => "Clock (Second Chance)";
public MemorySimulationResult Simulate(int[] referenceString, int numberOfFrames)
{
// Implementation
}
}- Add to memory menu in
MenuSystem.cs
Modify Visualizer.cs to add new chart types or formatting options.
- 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
All simulation results are logged to simulation.log when logging is enabled:
cat simulation.logLog entries include:
- Timestamp
- Algorithm name
- Process/page access details
- Summary statistics
- 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
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.jsonis in the project root, or it will be auto-created
Issue: Log file permission denied
- Solution: Check write permissions:
chmod +w simulation.log
MIT License - See LICENSE file for details.
Copyright (c) 2025 Mohamed Mostafa (mo7ammedd)
To contribute:
- Fork the repository
- Create a feature branch
- Implement your changes with proper documentation
- Submit a pull request
Mohamed Mostafa (@mo7ammedd)
- Website: modev.me
- Email: mohammedmostafanazih@gmail.com