OS

https://drive.google.com/drive/folders/1sIo0ceMnbNVOE0nAxouC6eN4uI_jnJ2e

a)   preemptive CPU Scheduling Algorithm--priority based

#include<stdio.h>
 // structure representing a structure
struct priority_scheduling {

  // name of the process
  char process_name;

  // time required for execution
  int burst_time;

  // waiting time of a process
  int waiting_time;

  // total time of execution
  int turn_around_time;

  // priority of the process
  int priority;
};

int main() {

  // total number of processes
  int number_of_process;

  // total waiting and turnaround time
  int total = 0;

  // temporary structure for swapping
  struct priority_scheduling temp_process;

  // ASCII numbers are used to represent the name of the process
  int ASCII_number = 65;

  // swapping position
  int position;

  // average waiting time of the process
  float average_waiting_time;

  // average turnaround time of the process
  float average_turnaround_time;

  printf("Enter the total number of Processes: ");
  // get the total number of the process as input
  scanf("%d", & number_of_process);

  // initializing the structure array
  struct priority_scheduling process[number_of_process];

  printf("\nPlease Enter the  Burst Time and Priority of each process:\n");

  // get burst time and priority of all process
  for (int i = 0; i < number_of_process; i++) {

    // assign names consecutively using ASCII number
    process[i].process_name = (char) ASCII_number;

    printf("\nEnter the details of the process %c \n", process[i].process_name);
    printf("Enter the burst time: ");
    scanf("%d", & process[i].burst_time);

    printf("Enter the priority: ");
    scanf("%d", & process[i].priority);

    // increment the ASCII number to get the next alphabet
    ASCII_number++;

  }

  // swap process according to high priority
  for (int i = 0; i < number_of_process; i++) {

    position = i;

    for (int j = i + 1; j < number_of_process; j++) {

      // check if priority is higher for swapping
      if (process[j].priority > process[position].priority)
        position = j;
    }
    // swapping of lower priority process with the higher priority process 
    temp_process = process[i];
    process[i] = process[position];
    process[position] = temp_process;
  }
  // First process will not have to wait and hence has a waiting time of 0
  process[0].waiting_time = 0;

  for (int i = 1; i < number_of_process; i++) {
    process[i].waiting_time = 0;
    for (int j = 0; j < i; j++) {
      // calculate waiting time
      process[i].waiting_time += process[j].burst_time;
    }

    // calculate total waiting time             
    total += process[i].waiting_time;
  }

  // calculate average waiting time
  average_waiting_time = (float) total / (float) number_of_process;

  // assigning total as 0 for next calculations
  total = 0;

  printf("\n\nProcess_name \t Burst Time \t Waiting Time \t  Turnaround Time\n");
  printf("------------------------------------------------------------\n");

  for (int i = 0; i < number_of_process; i++) {

    // calculating the turnaround time of the processes
    process[i].turn_around_time = process[i].burst_time + process[i].waiting_time;

    // calculating the total turnaround time.
    total += process[i].turn_around_time;

    // printing all the values
    printf("\t  %c \t\t  %d \t\t %d \t\t %d", process[i].process_name, process[i].burst_time, process[i].waiting_time, process[i].turn_around_time);
    printf("\n-----------------------------------------------------------\n");
  }

  // calculating the average turn_around time 
  average_turnaround_time = (float) total / (float) number_of_process;

  // average waiting time
  printf("\n\n Average Waiting Time : %f", average_waiting_time);

  // average turnaround time
  printf("\n Average Turnaround Time: %f\n", average_turnaround_time);

  return 0

} 


Non-preemptive CPU Scheduling Algorithm—Round  robin

#include<stdio.h>

#include<stdbool.h>

//  To find the waiting time 


void findWaitingTime(int processes[], int n,

int bt[], int wt[], int quantum)

{

//Store remaining burst time

int rem_bt[n],i;

for ( i = 0 ; i < n ; i++)

rem_bt[i] = bt[i];


int t = 0; // Current time

while (1)

{

bool done = true;

for ( i = 0 ; i < n; i++)

{

if (rem_bt[i] > 0)

{

done = false; // pending process


if (rem_bt[i] > quantum)

{

t += quantum;


rem_bt[i] -= quantum;

}

else

{

t = t + rem_bt[i];


// Waiting time = current time- time

// used in this process

wt[i] = t - bt[i];

                    //process is fully executed

rem_bt[i] = 0;

}

}

}


if (done == true)

break;

}

}


//  Calculate the turnaround time

void findTurnAroundTime(int processes[], int n,

int bt[], int wt[], int tat[])

{    int i;

for (i = 0; i < n ; i++)

tat[i] = bt[i] + wt[i];

}


//Calculate the average time

void findavgTime(int processes[], int n, int bt[],

int quantum)

{

int wt[n], tat[n], total_wt = 0, total_tat = 0;


//  Find waiting time of all processes

findWaitingTime(processes, n, bt, wt, quantum);


//Find turn around time for all processes

findTurnAroundTime(processes, n, bt, wt, tat);


printf( "PN\t ");

printf( " \tBT ");

    printf("  WT "); 

    printf(" \tTAT\n");

int i;

for ( i=0; i<n; i++)

{

total_wt = total_wt + wt[i];

total_tat = total_tat + tat[i];

printf("%d %d %d %d " ,i+1 , bt[i] ,

wt[i] , tat[i]);

 

}


printf("Average waiting time =%f ", (float)total_wt / (float)n);

printf( "\nAverage turn around time =%f ",

(float)total_tat / (float)n);

}


int main()

{

int processes[] = { 1, 2, 3};

int n = sizeof processes / sizeof processes[0];


// Burst time of all processes

int burst_time[] = {5, 4, 6};

int quantum = 2;

findavgTime(processes, n, burst_time, quantum);

return 0;

}


Producer consumer Problem

#include <stdio.h>

#include <stdlib.h>

// Initializing the mutex variable with the value 1.

int mutex = 1;

// Initializing the full variable with the value 0.

int full = 0;

// empty variable will store the number of empty slots in the buffer.

int empty = 10, data = 0;

// A function that will resemble producers' production of data

void producer()

{

    // decrementing the value of mutex

    --mutex;

    // Increase the number of full slots

    ++full;

    // decrementing the number of slots available

    --empty;

    // incrementing data which means that the data is produced.

    data++;

    printf("\nProducer produces item number: %d\n", data);

    // incrementing the value of mutex

    ++mutex;

}

// A function that will resemble the consumer's consumption of data

void consumer()

{

    // decrementing the value of mutex

    --mutex;

    // Decrease the number of full slots

    --full;

    // incrementing the number of slots available

    ++empty;


    printf("\nConsumer consumes item number: %d.\n", data);


    // since data is consumed, let us decrease the value of data

    data--;


    // incrementing the value of mutex

    ++mutex;

}


int main()

{

    int n, i;

    printf("\n1. Enter 1 for Producer"

           "\n2. Enter 2 for Consumer"

           "\n3. Enter 3 to Exit");


    for (i = 1; i > 0; i++)

    {

        printf("\nEnter your choice: ");

        scanf("%d", &n);


        // using switch case as there can be multiple types of choice.

        switch (n)

        {

        case 1:

            /*

            If the value of mutex is 1 and the buffer is not full, then we can produce the data

            */

            if ((mutex == 1) && (empty != 0))

            {

                producer();

            }


            // else, the buffer must be full.

            else

            {

                printf("The Buffer is full. New data cannot be produced!");

            }

            break;


        case 2:

            /*

            If the value of mutex is 1 and the buffer is not empty, then we can consume the data

            */

            if ((mutex == 1) && (full != 0))

            {

                consumer();

            }

            // else, the buffer must be empty.

            else

            {

                printf("The Buffer is empty! New data cannot be consumed!");

            }

            break;

        // Exit Condition

        case 3:

            exit(0);

            break;

        }

    }

}


Dining philosophers problem using semaphores

#include <pthread.h>

#include <semaphore.h>

#include <stdio.h>


#define N 5

#define THINKING 2

#define HUNGRY 1

#define EATING 0

#define LEFT (phnum + 4) % N

#define RIGHT (phnum + 1) % N


int state[N];

int phil[N] = { 0, 1, 2, 3, 4 };


sem_t mutex;

sem_t S[N];


void test(int phnum)

{

if (state[phnum] == HUNGRY

&& state[LEFT] != EATING

&& state[RIGHT] != EATING) {

// state that eating

state[phnum] = EATING;


sleep(2);


printf("Philosopher %d takes fork %d and %d\n",

phnum + 1, LEFT + 1, phnum + 1);


printf("Philosopher %d is Eating\n", phnum + 1);


// sem_post(&S[phnum]) has no effect

// during takefork

// used to wake up hungry philosophers

// during putfork

sem_post(&S[phnum]);

}

}


// take up chopsticks

void take_fork(int phnum)

{


sem_wait(&mutex);


// state that hungry

state[phnum] = HUNGRY;


printf("Philosopher %d is Hungry\n", phnum + 1);


// eat if neighbours are not eating

test(phnum);


sem_post(&mutex);


// if unable to eat wait to be signalled

sem_wait(&S[phnum]);


sleep(1);

}


// put down chopsticks

void put_fork(int phnum)

{


sem_wait(&mutex);


// state that thinking

state[phnum] = THINKING;


printf("Philosopher %d putting fork %d and %d down\n",

phnum + 1, LEFT + 1, phnum + 1);

printf("Philosopher %d is thinking\n", phnum + 1);


test(LEFT);

test(RIGHT);


sem_post(&mutex);

}


void* philosopher(void* num)

{


while (1) {


int* i = num;


sleep(1);


take_fork(*i);


sleep(0);


put_fork(*i);

}

}


int main()

{


int i;

pthread_t thread_id[N];


// initialize the semaphores

sem_init(&mutex, 0, 1);


for (i = 0; i < N; i++)


sem_init(&S[i], 0, 0);


for (i = 0; i < N; i++) {


// create philosopher processes

pthread_create(&thread_id[i], NULL,

philosopher, &phil[i]);


printf("Philosopher %d is thinking\n", i + 1);

}


for (i = 0; i < N; i++)


pthread_join(thread_id[i], NULL);

}


 C implementation of First - Fit algorithm

#include<stdio.h>


// Function to allocate memory to

// blocks as per First fit algorithm

void firstFit(int blockSize[], int m, int processSize[], int n)

{

int i, j;

// Stores block id of the

// block allocated to a process

int allocation[n];


// Initially no block is assigned to any process

for(i = 0; i < n; i++)

{

allocation[i] = -1;

}


// pick each process and find suitable blocks

// according to its size ad assign to it

for (i = 0; i < n; i++) //here, n -> number of processes

{

for (j = 0; j < m; j++) //here, m -> number of blocks

{

if (blockSize[j] >= processSize[i])

{

// allocating block j to the ith process

allocation[i] = j;


// Reduce available memory in this block.

blockSize[j] -= processSize[i];


break; //go to the next process in the queue

}

}

}


printf("\nProcess No.\tProcess Size\tBlock no.\n");

for (int i = 0; i < n; i++)

{

printf(" %i\t\t\t", i+1);

printf("%i\t\t\t\t", processSize[i]);

if (allocation[i] != -1)

printf("%i", allocation[i] + 1);

else

printf("Not Allocated");

printf("\n");

}

}


// Driver code

int main()

{

int m; //number of blocks in the memory

int n; //number of processes in the input queue

int blockSize[] = {100, 500, 200, 300, 600};

int processSize[] = {212, 417, 112, 426};

m = sizeof(blockSize) / sizeof(blockSize[0]);

n = sizeof(processSize) / sizeof(processSize[0]);


firstFit(blockSize, m, processSize, n);


return 0 ;

}


Worst Fit (Dynamic Memory allocation algorithm)

#include <stdio.h>

#include <string.h>


void worstFit(int blockSize[], int m, int processSize[], int n)

{

    int allocation[n];

    memset(allocation, -1, sizeof(allocation));


    for (int i = 0; i < n; i++)

    {

        int wstIdx = -1;

        for (int j = 0; j < m; j++)

        {

            if (blockSize[j] >= processSize[i])

            {

                if (wstIdx == -1)

                    wstIdx = j;

                else if (blockSize[wstIdx] < blockSize[j])

                    wstIdx = j;

            }

        }


        if (wstIdx != -1)

        {

            allocation[i] = wstIdx;

            blockSize[wstIdx] -= processSize[i];

        }

    }


    printf("\nProcess No.\tProcess Size\tBlock no.\n");

    for (int i = 0; i < n; i++)

    {

        printf(" %d\t\t%d\t\t", i + 1, processSize[i]);

        if (allocation[i] != -1)

            printf("%d", allocation[i] + 1);

        else

            printf("Not Allocated");

        printf("\n");

    }

}


int main()

{

    int blockSize[] = {100, 500, 200, 300, 600};

    int processSize[] = {212, 417, 112, 426};

    int m = sizeof(blockSize) / sizeof(blockSize[0]);

    int n = sizeof(processSize) / sizeof(processSize[0]);


    worstFit(blockSize, m, processSize, n);


    return 0;

}


LRU 

#include <stdio.h>

int main() {
    // memory's capacity to hold pages
    int size = 3;
  
    int reference_string[] = {1, 2, 1, 0, 3, 0, 4, 2, 4};
    int ref_string_size = sizeof(reference_string) / sizeof(reference_string[0]);

    // creating an array to store the current pages in memory
    int pages[size];
    int num_pages = 0;

    // page faults
    int faults = 0;

    // page hits
    int hits = 0;

    // iterating the reference string
    for (int i = 0; i < ref_string_size; i++) {
        int ref_page = reference_string[i];

        // check if ref_page already exists in pages array
        int found = 0;
        for (int j = 0; j < num_pages; j++) {
            if (pages[j] == ref_page) {
                found = 1;
                break;
            }
        }

        // if ref_page is found in pages array
        if (found) {
            // remove ref_page from its current position and append it at the end
            for (int j = 0; j < num_pages; j++) {
                if (pages[j] == ref_page) {
                    for (int k = j; k < num_pages - 1; k++) {
                        pages[k] = pages[k + 1];
                    }
                    pages[num_pages - 1] = ref_page;
                    break;
                }
            }

            // increment the page hits
            hits++;
        } else {
            // increment the page faults
            faults++;

            // check the length of the pages array
            if (num_pages < size) {
                // if length is less than memory size, append ref_page into pages array
                pages[num_pages] = ref_page;
                num_pages++;
            } else {
                // if length is greater than or equal to memory size, remove the first page of pages array
                // and append ref_page to the end
                for (int j = 0; j < num_pages - 1; j++) {
                    pages[j] = pages[j + 1];
                }
                pages[num_pages - 1] = ref_page;
            }
        }
    }

    // printing the number of page hits and page faults
    printf("Total number of Page Hits: %d\n", hits);
    printf("Total number of Page Faults: %d\n", faults);

    return 0;
}

Optimal 

#include <stdio.h>

/*
predictPage() that takes a frame array, index, and page array. It returns the predicted page.
*/
int predictPage(int page[], int frames[], int pageNumber, int pageIndex, int numFrames) {
    int result = -1, farthestPage = pageIndex;
    for (int i = 0; i < numFrames; i++) {
        int j;
        for (j = pageIndex; j < pageNumber; j++) {
            if (frames[i] == page[j]) {
                if (j > farthestPage) {
                    farthestPage = j;
                    result = i;
                }
                break;
            }
        }

        if (j == pageNumber)
            return i;
    }

    if (result == -1)
        return 0;
    else
        return result;
}

/*
searchPage() that takes a key and a frame array. It returns true if the key is found in the frame, else it returns false.
*/
int searchPage(int key, int frames[], int numFrames) {
    for (int i = 0; i < numFrames; i++) {
        // if the frame is found, return true
        if (frames[i] == key)
            return 1;
    }

    return 0;
}

/*
find() that takes a page array, frame number, and page number. It finds and prints the page hits and page misses.
*/
void find(int page[], int pageNumber, int frameNumber) {
    int frames[frameNumber];
    int hit = 0;
    for (int i = 0; i < pageNumber; i++) {
        if (searchPage(page[i], frames, frameNumber)) {
            // if found, increment the hit counter
            hit++;
            continue;
        }

        if (frameNumber > 0) {
            if (frameNumber > i) {
                frames[i] = page[i];
            } else {
                int j = predictPage(page, frames, pageNumber, i + 1, frameNumber);
                frames[j] = page[i];
            }
        }
    }

    // printing the hits and misses.
    printf("Page hits: %d\n", hit);
    printf("Page misses: %d\n", pageNumber - hit);
}

int main() {
    int page[] = {1, 7, 8, 3, 0, 2, 0, 3, 5, 4, 0, 6, 1};
    int pageNumber = sizeof(page) / sizeof(page[0]);
    int frameNumber = 3;
    find(page, pageNumber, frameNumber);

    return 0;
}


FIFO


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>

struct Node {
    int data;
    struct Node* next;
};

struct Queue {
    struct Node *front, *rear;
};

struct Node* newNode(int data)
{
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = NULL;
    return temp;
}

struct Queue* createQueue()
{
    struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
    q->front = q->rear = NULL;
    return q;
}

void enQueue(struct Queue* q, int data)
{
    struct Node* temp = newNode(data);
    if (q->rear == NULL) {
        q->front = q->rear = temp;
        return;
    }
    q->rear->next = temp;
    q->rear = temp;
}

struct Node* deQueue(struct Queue* q)
{
    if (q->front == NULL)
        return NULL;
    struct Node* temp = q->front;
    q->front = q->front->next;
    if (q->front == NULL)
        q->rear = NULL;
    return temp;
}

bool searchPage(struct Queue* q, int data)
{
    struct Node* temp = q->front;
    while (temp != NULL) {
        if (temp->data == data)
            return true;
        temp = temp->next;
    }
    return false;
}

int pageFaults(int pages[], int n, int capacity)
{
    struct Queue* q = createQueue();
    int pageFaults = 0;
    for (int i = 0; i < n; i++) {
        if (!searchPage(q, pages[i])) {
            pageFaults++;
            if (q->rear == NULL || q->rear->data == INT_MIN) {
                if (q->rear == NULL)
                    q->front = q->rear = newNode(pages[i]);
                else {
                    q->rear->data = pages[i];
                    q->front = q->rear;
                }
            }
            else {
                struct Node* temp = deQueue(q);
                temp->data = pages[i];
                enQueue(q, temp->data);
            }
        }
    }
    return pageFaults;
}

int main()
{
    int pages[] = {1, 3, 0, 3, 5, 6, 3};
    int capacity = 3;
    int n = sizeof(pages) / sizeof(pages[0]);

    int pageFaults = pageFaults(pages, n, capacity);

    printf("The total number of page faults are: %d\n", pageFaults);

    return 0;
}


Write a program to simulate Banker's Deadlock detection algorithm


// Banker's Algorithm
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here

int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4

int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}

int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;
}
}
if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}

return (0);

// This code is contributed by Deep Baldha (CandyZack)
}



Write a multithreaded program to multiply two given matrices

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_SIZE 100

// Structure to hold matrix data
typedef struct {
    int row;
    int col;
    int size;
    int (*matrixA)[MAX_SIZE];
    int (*matrixB)[MAX_SIZE];
    int (*result)[MAX_SIZE];
} MatrixData;

// Function to multiply matrices in a given row and column
void* multiplyMatrix(void* arg) {
    MatrixData* data = (MatrixData*)arg;
    int row = data->row;
    int col = data->col;
    int size = data->size;

    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += data->matrixA[row][i] * data->matrixB[i][col];
    }

    data->result[row][col] = sum;

    pthread_exit(NULL);
}

// Function to print a matrix
void printMatrix(int matrix[][MAX_SIZE], int size) {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int size;

    printf("Enter the size of the matrices: ");
    scanf("%d", &size);

    // Create matrices A, B, and result
    int matrixA[MAX_SIZE][MAX_SIZE];
    int matrixB[MAX_SIZE][MAX_SIZE];
    int result[MAX_SIZE][MAX_SIZE];

    printf("Enter elements of matrix A:\n");
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            scanf("%d", &matrixA[i][j]);
        }
    }

    printf("Enter elements of matrix B:\n");
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            scanf("%d", &matrixB[i][j]);
        }
    }

    // Create threads
    pthread_t threads[MAX_SIZE][MAX_SIZE];

    // Create matrix data for each thread
    MatrixData matrixData[MAX_SIZE][MAX_SIZE];

    // Multiply matrices using threads
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            matrixData[i][j].row = i;
            matrixData[i][j].col = j;
            matrixData[i][j].size = size;
            matrixData[i][j].matrixA = matrixA;
            matrixData[i][j].matrixB = matrixB;
            matrixData[i][j].result = result;

            pthread_create(&threads[i][j], NULL, multiplyMatrix, &matrixData[i][j]);
        }
    }

    // Wait for all threads to finish
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            pthread_join(threads[i][j], NULL);
        }
    }

    // Print the result matrix
    printf("Resultant matrix:\n");
    printMatrix(result, size);

    return 0;
}

Comments

Popular posts from this blog

RUINS TOP-UP

The Runawayz: Encounter