owned this note
owned this note
Published
Linked with GitHub
# CPU Task Scheduler Simulator with Shell Integration
Github Link : https://github.com/dennis15984/CPU-Task-Scheduler-Simulator-with-Shell-Integration
## Overview
A Unix-like shell integrated with a user-level task scheduler supporting three scheduling algorithms: Round Robin (RR), First-Come-First-Served (FCFS), and Preemptive Priority (PP). The system features command history, pipeline processing, I/O redirection, background job execution, resource management with 8 shared resources, task lifecycle tracking, and comprehensive timing statistics.
## Core Components
### 1. Shell Implementation (`shell.c`, `command.c`, `builtin.c`)
#### Shell Features
- **Command Parsing**: Tokenizes input and handles special characters
- **Pipeline Support**: Multi-stage command execution with pipes (`|`)
- **I/O Redirection**: Input (`<`) and output (`>`) redirection
- **Background Execution**: Asynchronous process execution (`&`)
- **Command History**: Record and replay previous commands
- **Built-in Commands**: System-level operations
#### Built-in Commands
| Command | Syntax | Description |
|---------|--------|-------------|
| `help` | `help` | Display available commands |
| `cd` | `cd [directory]` | Change working directory |
| `echo` | `echo [-n] [text]` | Print text to stdout |
| `exit` | `exit` | Terminate shell |
| `record` | `record` | Show command history |
| `replay` | `replay [number]` | Re-execute command from history |
| `mypid` | `mypid -i\|-p [pid]\|-c [ppid]` | Process information utilities |
| `add` | `add [name] [function] [priority]` | Create new task |
| `del` | `del [name]` | Delete task |
| `ps` | `ps` | Display task status |
| `start` | `start` | Begin task execution |
#### Command Processing Flow
```
User Input → Tokenization → Command Structure → Execution
↓
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ read_line() │ → │ split_line() │ → │ fork_pipes() or │
│ │ │ │ │ execute() │
│ - Input buffer │ │ - Parse tokens │ │ - Process mgmt │
│ - History mgmt │ │ - Handle pipes │ │ - I/O redirect │
│ - Replay logic │ │ - I/O redirect │ │ - Background │
└─────────────────┘ └─────────────────┘ └─────────────────┘
```
### 2. Task Scheduler (`task.c`)
#### Scheduling Algorithms
**First-Come-First-Served (FCFS)**
- Non-preemptive execution
- Tasks run to completion unless voluntarily yielding
- Simple FIFO queue processing
```c
void fcfs_algo() {
while(ready_idx != 0 && ready_queue->next != NULL) {
working_struct = ready_queue->next;
working_struct->status = RUNNING;
swapcontext(&main_task, &working_struct->task);
}
}
```
**Round Robin (RR)**
RR uses signals for time-based preemption. A virtual timer (SIGVTALRM) fires every 10 microseconds, tracking each task's CPU time. When a task reaches its 30ms time quantum, the signal handler forcibly interrupts it, saves its execution state, and returns control to the scheduler for the next task in the circular queue.
```c
// Timer interrupt every 10μs
if(time_quantum == 30 && ready_idx > 1 && strcmp(algo_type, rr_word) == 0) {
getcontext(&store_task);
working_struct->task = store_task;
time_quantum = 0;
setcontext(&main_task); // Return to scheduler
}
```
**Preemptive Priority (PP)**
Preemptive Priority (PP) uses the same signal mechanism but for priority-based preemption. The timer continuously monitors the ready queue - if a higher priority task becomes available (e.g., wakes up from sleep or gets added), the signal handler immediately preempts the current lower-priority task and switches to the higher-priority one.
```c
void* prior_select() {
task_struct* higher = ready_queue->next;
task_struct* temp = ready_queue->next;
for(int i = 0; i < ready_idx; i++) {
if(temp->priority < higher->priority) {
higher = temp;
}
temp = temp->next;
}
return higher;
}
```
#### Task State Management
```
┌─────────┐ create ┌─────────┐ schedule ┌─────────┐
│ CREATED │ ────────────→ │ READY │ ────────────→ │ RUNNING │
└─────────┘ └─────────┘ └─────────┘
↑ │
│ │ sleep/block
│ wakeup ↓
┌─────────┐ ┌─────────┐
│ WAITING │ │TERMINATED│
└─────────┘ └─────────┘
```
#### Task Structure
```c
typedef struct tasks {
ucontext_t task; // CPU execution context
task_state status; // Current state
char* task_name; // Identifier
int priority; // Scheduling priority
int TID; // Task ID
int running_time; // CPU time consumed
int waiting_time; // Time spent waiting
int turnaround_time; // Total lifetime
int sleep_time; // Sleep duration remaining
int resource_count; // Number of resources held
int* resources; // Resource ownership bitmap
int* resource_check; // Resource allocation tracking
int resource_flag; // Resource state indicator
struct tasks* next; // Queue linkage
struct tasks* previous; // Bidirectional linking
} task_struct;
```
### 3. Context Switching Mechanism
#### User-Level Context Management
The system implements cooperative multitasking using POSIX ucontext functions:
**Context Capture and Restoration**
```c
// Save current execution state
getcontext(&working_struct->task);
// Restore previous execution state
setcontext(&working_struct->task);
// Atomic save and switch
swapcontext(&main_task, &working_struct->task);
// Create new execution context
makecontext(&new_task->task, function_pointer, 0);
```
**Context Switch Flow**
```
Scheduler Context
│
├─ setcontext() ─────────→ Task Context
│ │
│ (task execution)
│ │
│ getcontext()
│ (voluntary yield)
│ │
←─ setcontext() ─────────────────┘
│
(next task selection)
```
### 4. Resource Management (`resource.c`)
#### Resource Allocation System
- **8 Shared Resources**: Numbered 0-7, each binary available/in-use
```c
int resource_flag[8] = {1,1,1,1,1,1,1,1}; // 1=available, 0=in-use
void get_resources(int count, int *resources) {
// Check availability
if(check_resource(count, working_struct->resources, working_struct->resource_check)) {
// Grant all requested resources atomically
for(int i = 0; i < count; i++) {
resource_flag[resources[i]]--;
working_struct->resource_check[resources[i]] = 1;
}
working_struct->resource_flag = 1;
} else {
// Block and wait
wait_resource();
}
}
```
#### Resource State Transitions
```
┌──────────────┐ request ┌──────────────┐
│ AVAILABLE │ ────────────→ │ IN USE │
└──────────────┘ └──────────────┘
↑ │
│ release │ (task holds resource)
└──────────────────────────────┘
```
### 5. Task Functions (`function.c`)
#### Computational Tasks
- **task1**: Bubble sort algorithm (CPU-intensive)
- **task2**: Matrix multiplication (memory-intensive)
- **task3**: Linear search operation (I/O simulation)
#### Resource Management Tasks
- **task4-9**: Various resource usage patterns
- **test_resource**: Resource allocation testing
#### Control Flow Tasks
- **test_exit**: Immediate termination
- **test_sleep**: Sleep/wake cycle testing
- **idle**: Infinite loop for system testing
## Compilation and Usage
### Build System
```makefile
TARGET = scheduler_simulator
CC = gcc
FLAGS = -Wall -pthread
OBJ = builtin.o command.o shell.o function.o resource.o task.o
INCLUDE = ./include/
SRC = ./src/
all: $(TARGET)
$(TARGET): main.c $(OBJ)
$(CC) $(FLAGS) -o $(TARGET) $(OBJ) $<
%.o: ${SRC}%.c ${INCLUDE}%.h
$(CC) $(FLAGS) -c $<
.PHONY: clean
clean:
rm -f ${TARGET} *.o out*
clean_obj:
rm -f *.o
```
### Execution
```bash
./scheduler_simulator [ALGORITHM]
```
Where `[ALGORITHM]` is one of: `FCFS`, `RR`, `PP`
## Usage Examples
### Basic Task Management
```bash
# Start shell with Round Robin scheduling
./scheduler_simulator RR
# Create tasks with different priorities
>>> $ add sorting_task task1 5
>>> $ add matrix_task task2 3
>>> $ add search_task task3 7
# View current task queue
>>> $ ps
# Begin execution
>>> $ start
# Monitor execution and return to shell
>>> $ ps
>>> $ exit
```
### Shell Operations
```bash
# Command history
>>> $ echo "test command"
>>> $ record
>>> $ replay 1
# Pipeline operations
>>> $ cat input.txt | grep "pattern" | sort > output.txt
# Background execution
>>> $ long_running_command &
# Process information
>>> $ mypid -i
>>> $ mypid -p 1234
>>> $ mypid -c 5678
```
### Resource Management Demo
```bash
>>> $ add resource_user task4 1
>>> $ add resource_competitor task5 2
>>> $ start
# Observe resource contention and blocking
>>> $ ps
```
## Testing Framework
### Automated Scheduler Testing
```bash
# Test single algorithm
python3 auto_run.py FCFS test_case1.txt
# Test all algorithms
python3 auto_run.py all general.txt
```
### Shell Functionality Testing
```bash
# Comprehensive shell testing
python3 judge_shell.py all
# Specific feature testing
python3 judge_shell.py 1.1 2.3 # Test external commands and record/replay
```
## Performance Metrics
### Timing Statistics
- **Running Time**: CPU cycles consumed by task
- **Waiting Time**: Time spent in ready queue
- **Turnaround Time**: Total time from creation to completion
- **Response Time**: Time to first execution
### Task Status Display
```
TID| name| state| running| waiting| turnaround| resources| priority
----------------------------------------------------------------------------------------------
1 task1_sort RUNNING 45 12 57 1 3 5 5
2 task2_matrix READY 0 30 30 none 3
3 task3_search TERMINATED 120 25 145 none 7
```