OS Lab Assignment || Das Edition || B. Tech Diaries

OS Lab

Assignment #1

Perform the following operations

  1. Create three directories named letter, report and assignment.
    
    mkdir letter
    mkdir report
    mkdir assignment
  2. Move to directory letter.
    
    cd letter
  3. Create two directories named friendly and formal under letter directory.
    
    mkdir friendly formal
  4. Move to directory report using only one command (from directory letter)
    
    cd ../report
  5. Create three directories called personal, business, school under directory report (Using one command).
    
    mkdir ../assignment/unit
  6. Create a directory called unit under the assignment directory without moving from the directory report (Using one command).
    
    mkdir personal business school
  7. Move to your HOME directory.
    
    cd ~
  8. Recursively list all the directories you have created and draw the directory structure.
    
    ls -LR

Assignment #2

Perform the following operations

  1. Change the working directory to friendly and use pluma from the command line to create A1.text with the following personal information.
    Name: <student_name>
    Email: <email_id>
    Id: <student_id>
    Date: <date>
    
    cd friendly
    pluma A1.text
    
    Name:   Purbayan Chowdhury
    Email:  pur.cho.99@gmail.com
    Id:     90
    Date:   01/02/2020
  2. Exit pluma and copy the new file A1.txt to B1.txt. Verify that both files exist by listing the directory.
    
    cp A1.txt B1.txt
    ls
    # A1.txt B1.txt
  3. Rename the B1.txt file to A.txt, then list the directory, and remove the A1.txt file, and list the directory again.
    
    mv B1.txt A.txt
    rm A1.txt
    ls
    # A.txt
  4. Set A.txt to have read and write permission for the owner, but keep file private from others.
    
    chmod 600 A.txt
  5. Now check the file permissions for A.txt.
    
    ls -l
    # total 4
    # -rw------- 1 pur.cho.99 pur.cho.99 0 Jan  2  2020 A.txt
  6. Move to your HOME directory.
    
    cd ~
  7. Recursively list all the directories you have created and draw the directory structure.
    
    ls -LR

Assignment #3

Perform the following operations using date and cal command.

  1. Display 3 months from now
    
    cal -A2
  2. Display Monday as the first day
    
    ncal -M
  3. Display September of 1752
    
    cal -m 9 1752
  4. Display 3 months for the data around 9th March 2015
    
    ncal -m 3 2015 -A2 -H 2015-03-09
  5. Display day of the week
    
    date +%A
  6. Display week number of the year
    
    date +%V
  7. Display date on this format - 12th April 1998
    
    date +'%_d %_B %_Y'
  8. Display date on this format - 12th Jan'95
    
    date +"%_d %_b'%_y"
  9. Display date on this format - 05/07/98
    
    date +%d/%m/%y
  10. Display current date with hour minute second
    
    date +%H:%M:%S

Assignment #4

Open a terminal window and show the manual page for the command grep.

Suppose that you have a file abc.txt whose contents are

  1. Your name in sentence case.
  2. Your name in capital case.
  3. Your name in small case.
  4. Email id.
  5. Mobile number.
  6. Phone number.
  7. Your hobby.
  8. A blankline.
  9. Your grade in Data Structures and Algorithms.
  10. Any special character.
  11. A string like 112@456.
  12. Dates in different format.

Write the grep command for the following instructions:

  1. Find your name in small letter.
    
    grep "^[a-z]+ [a-z]+$" abc.txt
    # purbayan chowdhury
  2. Find your name anywhere in file.
    
    grep -i "^[a-z]+ [a-z]+$" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
  3. Show two lines before & after your hobby.
    
    grep -A2 -B2 "^Hobby: [a-zA-Z]+$" abc.txt
    # Hobby: cricket
    #
    # A+
  4. Show your mail id.
    
    grep -i "^[a-z_]+[a-z0-9._]+@[a-z]{3,}.[a-z]{2,}$" abc.txt
    # pur.cho.99@gmail.com
  5. Show all the lines containing @.
    
    grep "@" abc.txt
    # pur.cho.99@gmail.com
    # 112@456
  6. Show all the lines without @.
    
    grep -v "@" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
    # 7898765432
    # +91789765432
    # Hobby: cricket
    #
    # A+
    # 112@456
    # 12/08/2020
  7. Find how many times your name is present in the file.
    
    grep -c "^[a-zA-Z]+ [a-zA-Z]+$" abc.txt
    # 3
  8. Find the line number where your name is present in the file in small case or capital.
    
    grep -n "^[a-z]+ [a-z]+$|^[A-Z]+ [A-Z]+$|" abc.txt
    # 2:PURBAYAN CHOWDHURY
    # 3:purbayan chowdhury
  9. Print all lines that contain a mobile number.
    
    grep "^[0-9]{10}$" abc.txt
    # 7898765432
  10. Print all lines that contain a phone number with an extension.
    
    grep "^[0-9]{2,3}[-][0-9]{6,8}$" abc.txt
    # +91789765432
  11. Print all lines containing a vowel.
    
    grep -i "[aeiou]" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
    # pur.cho.99@gmail.com
    # Hobby: cricket
  12. Print all lines that do not begin with a capital S.
    
    grep -v "^S" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
    # 7898765432
    # +91789765432
    # Hobby: cricket
    #
    # A+
    # 112@456
    # 12/08/2020
  13. Is there any day of a date?
    
    grep -i "^[0-3][0-9]/[0-9]{2}/[0-9]{4}$" abc.txt
    # 12/08/2020

Assignment #5

  • Write a program to print current process ID, parent process ID and child process ID.
    
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int main()
    {
        pid_t pid, ppid, cpid;
    
        pid = getpid();
        ppid = getppid();
        cpid = fork();
    
        printf("Process ID: %d\n", pid);
        printf("Parent Process ID: %d\n", ppid);
        printf("Child Process ID: %d\n", cpid);
    
        return 0;
    }
    
    Process ID: 8
    Parent Process ID: 7
    Child Process ID: 0
  • Show that the orders of print statement in the child and parent process are different at different times of execution. Find the reason behind it.
    
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int main()
    {
        if(fork()==0)
            printf("Child \n");
        else
            printf("Parent \n");
        return 0;
    }
    
    Parent
    Child
    On the execution, both programs (parent and child) will execute independent of each other starting from if statement. In the parent, since pid is non-zero, it prints the parent and on the child, since pid is zero, it prints the child later.
  • Show that parent process ID depends on Shell.
    
    gcc -o exe process1.c
    ./exe
    # Current process: 3148
    # Parent process: 3141
    
    
    gcc -o exe process1.c
    ./exe
    # Current process: 3156
    # Parent process: 3149
    The reason for this is that the parent process ID depends on the Shell.
  • Write a C program using fork() system call that generates the Fibonacci sequence in the child process. The number of the sequence will be provided in the command line. For example, if 5 is provided, the first five numbers in Fibonacci will be output by the childd process. Because the parent and child processes have their own copies of the data, it will be necessary for child to output the sequence.
    
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int main()
    {
        int a=0, b=1, c=a+b, i, ii;
        pid_t pid;
        printf("Enter the number of terms: ");
        scanf("%d", &ii);
        if(ii<=0)
        {
            printf("Please enter a positive number.\n");
            return 0;
        } else {
            pid = fork();
            if(pid == 0)
            {
                printf("Child is producing the Fibonacci series.....\n");
                for(i=0; i<ii; i++)
                {
                    printf("%d ", c);
                    a=b;
                    b=c;
                    c=a+b;
                }
                printf("\n");
                printf("Child ends.\n");
            } else {
                printf("Parent is waiting for child to finish......\n");
                wait(NULL);
                printf("Parent ends.\n");
            }
        }
        return 0;
    }
    
    /*
    Output:
    */
    
    Enter the number of terms: 5
    Parent is waiting for child to finish......
    Child is producing the Fibonacci series.....
    0 1 1 2 3 5
    Child ends.
    Parent ends.

Assignment #6

  1. Take two numbers through command line argument. Write a shell script to interchange the contents of the variables. Do the same operation without using any third variable.
    
    #!/bin/bash
    file1=$1
    file2=$2
    echo "Before swapping: "$file1 $file2
    temp=$file1
    file1=$file2
    file2=$temp
    echo "After swapping: "$file1 $file2
    
    
    Before swapping: 1 2
    After swapping: 2 1
    
    #!/bin/bash
    file1=$1
    file2=$2
    echo "Before swapping: "$file1 $file2
    file1=$((file1 + file2))
    file2=$((file1 - file2))
    file1=$((file1 - file2))
    echo "After swapping: "$file1 $file2
    
    Before swapping: 1 2
    After swapping: 2 1
  2. Write a shell script to check whether a given year is leap year or not.
    
    #!/bin/bash
    year=$1
    y=$((!(year % 4) && (year % 100 || !(year % 400))))
    if [ $y -eq 1 ]; then
        echo "$year is a leap year"
    else
        echo "$year is not a leap year"
    fi
    
    Enter the year: 2000
    2000 is a leap year
  3. Write a shell script to find the value of y using
    Y(x, n) = {1+x^2 when n=1}
              {1+x/n when n=2}
              {1+2x when n=3}
              {1+nx when n>3 or n<1}
    
    
    #!/bin/bash
    x=$1
    n=$2
    if [ $n -lt 1 ]; then
        echo "Enter a positive number"
    elif [ "$n" -eq "1" ]; then
        echo $((1+x*x))
    elif [ "$n" -eq "2" ]; then
        echo $((1+x/n))
    elif [ "$n" -eq "3" ]; then
        echo $((1+2*x))
    else
        echo $((1+n*x))
    fi
  4. Determine grade as per following rules using a switch case:
    • If marks are more than 90, grade is O
    • If marks are more than 80, grade is E
    • If marks are more than 70, grade is A
    • If marks are more than 60, grade is B
    • If marks are more than 50, grade is C
    • If marks are less than 50, grade is F
    
    #!/bin/bash
    marks=$1
    case $marks in
        [9][0-9]|100)
            echo "O grade"
            ;;
        [8][0-9]|[8][0-9][0-9])
            echo "E grade"
            ;;
        [7][0-9]|[7][0-9][0-9])
            echo "A grade"
            ;;
        [6][0-9]|[6][0-9][0-9])
            echo "B grade"
            ;;
        [5][0-9]|[5][0-9][0-9])
            echo "C grade"
            ;;
        [4][0-9]|[4][0-9][0-9]|[3][0-9]|[3][0-9][0-9])
            echo "F grade"
            ;;
        *)
            echo "Invalid marks"
            ;;
    esac
    
    
    
    Enter the marks: 90
    O grade

Assignment #7,8,9

Write a program to implement the following scheduling.

  • First Come First Served Scheduling
  • Priority Scheduling
  • Shortest Job First Scheduling
  • Round Robin Scheduling
  • Shortest Remaining Time First Scheduling

#include <iostream>
#include <algorithm>

class process
{
    int _id, _atime, _ttime, _btime, _wtime, _priority;

public:
    process()
    {
        _id = 0;
        _atime = 0;
        _ttime = 0;
        _btime = 0;
        _wtime = 0;
        _priority = 0;
    }
    process(int id, int atime, int btime, int priority = 0)
    {
        this->_id = id;
        this->_atime = atime;
        this->_btime = btime;
        this->_ttime = 0;
        this->_wtime = 0;
        this->_priority = priority;
    }
    void print()
    {
        printf("%d\t%d\t%d\t%d\t%d\t%d\n", this->_id, this->_btime, this->_atime, this->_ttime, this->_wtime, this->_priority);
    };
    int id()
    {
        return this->_id;
    }
    int atime()
    {
        return this->_atime;
    }
    int btime()
    {
        return this->_btime;
    }
    int ttime()
    {
        return this->_ttime;
    }
    int wtime()
    {
        return this->_wtime;
    }
    int priority()
    {
        return this->_priority;
    }

    void t_time(int ttime)
    {
        this->_ttime = ttime;
    };
    void w_time(int wtime)
    {
        this->_wtime = wtime;
    };
};

void fcfs(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return p1.atime() < p2.atime(); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
    {
        if (ctime - p[i].atime() < 0)
            ctime += p[i].atime();
        ctime += p[i].btime();
        p[i].t_time(ctime - p[i].atime());
        avg_t_time += p[i].ttime();
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void psa(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.priority() < p2.priority()) || (p1.priority() == p2.priority() && p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
    {
        if (ctime - p[i].atime() < 0)
            ctime += p[i].atime();
        ctime += p[i].btime();
        p[i].t_time(ctime - p[i].atime());
        avg_t_time += p[i].ttime();
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void sjf(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.btime() < p2.btime()) || (p1.btime() == p2.btime() && p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
    {
        if (ctime - p[i].atime() < 0)
            ctime += p[i].atime();
        ctime += p[i].btime();
        p[i].t_time(ctime - p[i].atime());
        avg_t_time += p[i].ttime();
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\tPriority\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void rr(process *p, int n, int quantum = 4)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    int min = -1, st[n], left_jobs = n;

    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
        st[i] = p[i].btime();

    while (left_jobs > 0)
    {
        for (i = 0; i < n; i++)
        {
            if (st[i] == 0 || ctime < p[i].atime())
                continue;
            if (st[i] > quantum)
            {
                ctime += quantum;
                st[i] -= quantum;
            }
            else
            {
                ctime += st[i];
                st[i] = 0;
                p[i].t_time(ctime - p[i].atime());
                avg_t_time += p[i].ttime();
                left_jobs--;
            }
        }
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\tPriority\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void srtf(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    int min = -1, st[n], left_jobs = n;

    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
        st[i] = p[i].btime();

    while (left_jobs != 0)
    {
        min = -1;
        for (i = 0; i < n; i++)
        {
            if (st[i] == 0 || ctime < p[i].atime())
                continue;
            if (min == -1 || st[i] < st[min])
                min = i;
        }
        ctime++;
        st[min]--;
        if (st[min] == 0)
        {
            left_jobs--;
            p[min].t_time(ctime - p[min].atime());
            avg_t_time += p[min].ttime();
        }
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\tPriority\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

int main()
{
    int n;
    n = 5;
    process p[n];

    // Process p1
    p[0] = process(1, 0, 24, 1);
    // Process p2
    p[1] = process(2, 3, 12, 4);
    // Process p3
    p[2] = process(3, 2, 6, 3);
    // Process p4
    p[3] = process(4, 0, 18, 0);
    // Process p5
    p[4] = process(5, 4, 3, 3);

    printf("\nFCFS:\n");
    fcfs(p, n);
    printf("\nPSA:\n");
    psa(p, n);
    printf("\nSJF:\n");
    sjf(p, n);
    printf("\nSRTF:\n");
    srtf(p, n);
    printf("\nRR:\n");
    rr(p, n);

    return 0;
}

FCFS:
Id	B_Time	A_Time	T_Time	W_Time
1	24	0	24	0	1
2	12	3	57	45	4
3	6	2	46	40	3
4	18	0	42	24	0
5	3	4	59	56	3
Average TAT: 	45
Average WT: 	33

PSA:
Id	B_Time	A_Time	T_Time	W_Time
1	24	0	42	18	1
2	12	3	60	48	4
3	6	2	46	40	3
4	18	0	18	0	0
5	3	4	47	44	3
Average TAT: 	42
Average WT: 	30

SJF:
Id	B_Time	A_Time	T_Time	W_Time	Priority
1	24	0	67	43	1
2	12	3	22	10	4
3	6	2	11	5	3
4	18	0	43	25	0
5	3	4	3	0	3
Average TAT: 	29
Average WT: 	16

SRTF:
Id	B_Time	A_Time	T_Time	W_Time	Priority
1	24	0	63	39	1
2	12	3	20	8	4
3	6	2	9	3	3
4	18	0	39	21	0
5	3	4	3	0	3
Average TAT: 	26
Average WT: 	14

RR:
Id	B_Time	A_Time	T_Time	W_Time	Priority
1	24	0	63	39	1
2	12	3	42	30	4
3	6	2	27	21	3
4	18	0	59	41	0
5	3	4	15	12	3
Average TAT: 	41
Average WT: 	28
Share:

Programming with C++ - Day1 || Wong Edition || B.Tech Diaries

Lab #1 - C++ Basics (Loops, Functions, Arrays)

  1. A software company sells a package that retails for $99. Quantity discounts are given according to the following table.

    Quantity Discount
    10-19 20%
    20-49 30%
    50-99 40%
    100 or more 50%

    Write a program that asks for the number of units sold and computes the total cost of the purchase. Declare the discount as constants.Input Validation: Make sure the number of units is greater than 0.

    
    #include <iostream>
    
    int main(int argc, char const *argv[])
    {
        int qty;
        // std::cout << "Enter no of units sold: ";
        while (std::cin >> qty)
        {
            if (qty > 0)
                break;
            std::cout << "No of units should be greater than 0" << std::endl;
            // std::cout << "Enter no of units sold: ";
        }
        double dis = 0;
        if (qty < 20)
            dis = 0.2;
        else if (qty < 50)
            dis = 0.3;
        else if (qty < 100)
            dis = 0.4;
        else
            dis = 0.5;
        double price = qty * 99 * (1 - dis);
        printf("\nTotal price is: %.2lf\n", price);
        return 0;
    }
  2. Write a program that generates the day's sales report for five stores. The program asks for the sales figures as input anddisplays a bar graph comparing each store's sales.Create each bar in the bar graph by displaying a row of asterisks. Each asterisk represents $100 of sales.Here is an example of the program's output.

    
    Date: July 22, 2019
    Name of Sales Manager: Tutu Pal
    CityCentre:   **********
    Park Street:  ************
    Rajarhat:     ******************
    South City:   ********
    Dum Dum:      *******************
    The store with the top sales on July 22, 2019 is Dum Dum.
    The total sales is $xxxx.

    Use the function void printbar(string store, int sales) to generate the bar chart.

    
    #include <iostream>
    
    void printbar(std::string store, double sales, double sales_max)
    {
        std::cout << store << ": \t";
        for (int j = 0; j < int(sales * 50.0 / sales_max); j++)
        {
            std::cout << "*";
        }
        std::cout << std::endl;
    }
    
    int main(int argc, char const *argv[])
    {
        std::string date = "July 22, 2019", manager = "Tutu Pal";
        std::string store_names[5] = {"City Centre", "Park Street", "Rajarhat", "South City", "Dum Dum"};
        double store_sales[5], total_sales = 0;
        int max = 0;
    
        for (int i = 0; i < 5; i++)
        {
            // std::cout << "Enter sales for store " << i + 1 << ": ";
            std::cin >> store_sales[i];
            total_sales += store_sales[i];
            if (store_sales[max] < store_sales[i])
                max = i;
        }
        std::cout << "\nDate:\t" << date << "\nName of Sales Manager:\t" << manager << std::endl;
    
        for (int i = 0; i < 5; i++)
        {
            printbar(store_names[i], store_sales[i], store_sales[max]);
        }
    
        std::cout << "\nThe store with the top sales on " << date << " is " << store_names[max] << std::endl;
        printf("\nThe total sales is $%.2lf.\n\n", total_sales);
        return 0;
    }
  3. Write a C++ program to implement the Number Guessing Game. In this game the computer chooses a random number between 1 and 100, and the player tries to guess the number in as few attempts as possible. Each time the player enters a guess, the computer tells him whether the guess is too high, too low, or right. Once the player guesses the number, the game is over.

    
    #include <iostream>
    
    int main(int argc, char const *argv[])
    {
        std::cout << "======NUMBER GUESSING GAME=======" << std::endl;
        int guess, number = rand() % 200 + 1;
        std::cout << "Guess a number between 1 and 200" << std::endl;
        std::cin >> guess;
        while (guess != number)
        {
            if (guess > number)
            {
                std::cout << "Your guess is too high!!" << std::endl;
            }
            else
            {
                std::cout << "Your guess is too low!!" << std::endl;
            }
            std::cin >> guess;
        }
        std::cout << "You guessed the number " << number << std::endl;
        return 0;
    }
Share:

OS Lab Project || Das Edition || B.Tech Diaries

Multilevel Queue Scheduling

Multilevel Queue Scheduling in Operating System

A multilevel queue scheduling is a scheduling algorithm where there are multiple queues for each type of process. The selection of level is done through priority based scheduling while each level queue scheduling are dependent entirely on the type of process. Round robin for upper layers and First come first served for lower layers. 

Source Code


/** 
 * @author  Purbayan Chowdhury
 * @brief   Multilevel Feedback Queue Scheduling Algorithm 
*/

#include <bits/stdc++.h>

class process
{
public:
    int _id, _atime, _wtime, _ttime, _btime, _priority, _percent;
    process(int id = 0, int atime = 0, int btime = 0, int priority = 0) : _id(id), _atime(atime), _btime(btime), _priority(priority), _percent(btime) {}
};

/**
 * Q3 = Batch Process having Low Priority with FCFS Algorithm 
 * Q2 = Interactive Process having Medium Priority with Priority Scheduling 
 * Q1 = System Process having High Priority with Round Robin Algorithm
*/

std::vector<process *> sortArrivalTime(std::vector<process *> p)
{
    int i, j;
    process *k;
    for (i = 0; i < p.size() - 1; i++)
    {
        for (j = p.size() - 1; j >= i + 1; j--)
        {
            if (p[j]->_atime < p[j - 1]->_atime)
            {
                k = p[j - 1];
                p[j - 1] = p[j];
                p[j] = k;
            }
        }
    }
    return p;
}

int FCFS(std::vector<process *> p, int stime, int etime)
{
    int i, c = etime - stime;
    if (c <= 0)
        return etime;
    for (i = 0; i < p.size(); i++)
    {
        if (p[i]->_percent > c)
        {
            p[i]->_percent -= c;
            return etime;
        }
        else
        {
            c = c - p[i]->_percent;
            p[i]->_ttime = stime + p[i]->_percent;
            stime += p[i]->_percent;
            p[i]->_percent = 0;
        }
    }
    return etime - c;
}

std::vector<process *> sortPriority(std::vector<process *> p)
{
    int i, j;
    process *k;
    for (i = 0; i < p.size() - 1; i++)
    {
        for (j = p.size() - 1; j >= i + 1; j--)
        {
            if (p[j]->_atime < p[j - 1]->_atime && (p[j]->_atime < p[j - 1]->_atime && p[j]->_priority < p[j - 1]->_priority))
            {
                k = p[j - 1];
                p[j - 1] = p[j];
                p[j] = k;
            }
        }
    }
    return p;
}

int PR(std::vector<process *> p, int stime, int etime)
{
    p = sortPriority(p);
    int i, c = etime - stime;
    if (c <= 0)
        return etime;
    for (i = 0; i < p.size(); i++)
    {
        if (p[i]->_percent > c)
        {
            p[i]->_percent -= c;
            return etime;
        }
        else
        {
            c = c - p[i]->_percent;
            p[i]->_ttime = stime + p[i]->_percent;
            stime += p[i]->_percent;
            p[i]->_percent = 0;
        }
    }
    return etime - c;
}

int RR(std::vector<process *> p, int stime, int etime)
{
    int i = 0, j, c = etime - stime, ct = p.size();
    int quantum = 4;
    while (ct != 0 && c != 0)
    {
        if (c < quantum)
        {
            if (p[i]->_percent > c)
            {
                p[i]->_percent -= c;
                return etime;
            }
            else
            {
                c = c - p[i]->_percent;
                p[i]->_ttime = stime + p[i]->_percent;
                stime += p[i]->_percent;
                p[i]->_percent = 0;
                ct--;
            }
            i++;
            if (i == p.size())
                break;
        }
        else
        {
            if (p[i]->_percent != 0)
            {
                if (p[i]->_percent > quantum)
                {
                    stime += quantum;
                    p[i]->_percent -= quantum;
                    c -= quantum;
                }
                else
                {
                    stime += p[i]->_percent;
                    p[i]->_ttime = stime;
                    c -= p[i]->_percent;
                    p[i]->_percent = 0;
                    ct--;
                }
            }
            i++;
            i = i % p.size();
        }
    }
    return etime - c;
}

std::vector<int> calculateTime(std::vector<process *> p)
{
    std::vector<int> t(2);
    t[0] = t[1] = 0;
    int i;
    for (i = 0; i < p.size(); i++)
    {
        p[i]->_ttime -= p[i]->_atime;
        t[0] += p[i]->_ttime;
        p[i]->_wtime = p[i]->_ttime - p[i]->_btime;
        t[1] += p[i]->_wtime;
    }
    return t;
}

void displayTime(std::vector<process *> p)
{
    std::cout << std::setfill(' ') << std::setw(10) << "Id"
              << std::setfill(' ') << std::setw(10) << "Priority"
              << std::setfill(' ') << std::setw(10) << "A_Time"
              << std::setfill(' ') << std::setw(10) << "B_Time"
              << std::setfill(' ') << std::setw(10) << "T_Time"
              << std::setfill(' ') << std::setw(10) << "W_Time"
              << std::endl;
    for (int i = 0; i < p.size(); i++)
        std::cout << std::setfill(' ') << std::setw(10) << p[i]->_id
                  << std::setfill(' ') << std::setw(10) << p[i]->_priority
                  << std::setfill(' ') << std::setw(10) << p[i]->_atime
                  << std::setfill(' ') << std::setw(10) << p[i]->_btime
                  << std::setfill(' ') << std::setw(10) << p[i]->_ttime
                  << std::setfill(' ') << std::setw(10) << p[i]->_wtime
                  << std::endl;
}

void displayPercent(std::vector<process *> p)
{
    int i;
    for (i = 0; i < p.size(); i++)
        printf("%d\t", p[i]->_percent);
    printf("\n");
}

int main(int argc, char const **argv)
{
    std::vector<process *> q[3];
    int n = 10, i, j, c = 10;
    std::vector<process *> p(n);
    std::vector<process> cp(n); // 10 Processes
    cp[0] = process(1, 7, 5, 1);
    cp[1] = process(2, 4, 2, 0);
    cp[2] = process(3, 5, 7, 1);
    cp[3] = process(4, 0, 6, 0);
    cp[4] = process(5, 3, 24, 0);
    cp[5] = process(6, 7, 4, 2);
    cp[6] = process(7, 0, 7, 1);
    cp[7] = process(8, 3, 12, 2);
    cp[8] = process(9, 2, 7, 1);
    cp[9] = process(10, 4, 8, 2);
    for (i = 0; i < n; i++)
        p[i] = &cp[i];
    p = sortArrivalTime(p);
    int pburst = 0, pend = 0;
    int co = 0;
    // displayPercent(p);
    while (c != 0)
    {
        c = 10;
        for (i = 0; i < n; i++)
        {
            if (p[i]->_percent != 0)
            {
                if (p[i]->_atime <= pburst)
                {
                    q[p[i]->_priority].push_back(p[i]);
                }
                else
                {
                    pend = p[i]->_atime;
                    break;
                }
            }
        }
        if (pend == pburst)
            pend = 999;
        for (j = 0; j < 3; j++)
        {
            switch (j)
            {
            case 0:
                if (!(q[j].empty()))
                    pburst = RR(q[j], pburst, pend);
                break;
            case 1:
                if (!(q[j].empty()))
                    pburst = PR(q[j], pburst, pend);
                break;
            case 2:
                if (!(q[j].empty()))
                    pburst = FCFS(q[j], pburst, pend);
                break;
            }
            if (pburst == pend)
                break;
        }
        for (i = 0; i < n; i++)
            if (p[i]->_percent == 0)
                c--;
        q[0].clear();
        q[1].clear();
        q[2].clear();
    }
    std::vector<int> t = calculateTime(p);
    displayTime(p);
    printf("Average Turnaround Time: %d\nAverage Waiting Time: %d\n", t[0], t[1]);
    return 0;
}


Share: