蔡承璋
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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 | ### 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 the current execution context into working_struct->task. // This allows the task to be resumed later from this exact point. getcontext(&working_struct->task); // Restore and switch to the saved execution context in working_struct->task. // Control will transfer to wherever this context was last saved. setcontext(&working_struct->task); // Save the current context into main_task and immediately switch to working_struct->task. // When the task finishes or yields, it can return back to main_task. swapcontext(&main_task, &working_struct->task); ``` ### 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 ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully