0% found this document useful (0 votes)
15 views

OSrec

Uploaded by

mr.dhanush.j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

OSrec

Uploaded by

mr.dhanush.j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

IMPLEMENTATION OF SCHEDULING ALGORITHM (CPU)

(d)ROUND ROBIN SCHEDULING

PROGRAM CODE:
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
struct process
{
int pro, brt, tt, wt, remt;
} pr[MAX];

int main()
{
int i, n, totwt = 0, tottt = 0, ts, totbrt = 0;
float avgwt, avgtt;

printf(“\n\tRound robin scheduling”);


printf(“\n---------------------------------“);
printf(“\n Enter the no. of process: “);
scanf(“%d”, &n);
printf(“\n Enter the time slice: “);
scanf(“%d”, &ts);
for (i= 0; i < n; i++)
{
printf(“\n process no: %d”, i + 1);
pr[i].pro =i+ 1;

printf(“\nEnter The Burst time:”);


scanf(“%d”, &pr[i].brt);
pr[i].remt = pr[i].brt;
totbrt += pr[i].brt;
}

int tott = 0;
while (tott < totbrt)
{
for (i = 0; i < n; i++)
{
if (pr[i].remt == 0)
continue;
if (pr[i].remt > ts)
{
tott += ts;
pr[i].remt -= ts;
}
else
{
tott += pr[i].remt;
pr[i].wt = tott – pr[i].brt;
pr[i].tt = tott;
pr[i].remt = 0;
}
}
}

printf(“\nProcess no:\tBurst time:\tWaiting time:\tTurn around time:”);


printf(“\n……….\t……….\t……….\t……….”);

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


{
printf(“\n%d\t\t%d\t\t%d\t\t%d”, pr[i].pro, pr[i].brt, pr[i].wt,
pr[i].tt);
totwt += pr[i].wt;
tottt += pr[i].tt;
}

avgwt = (float)totwt / n;
avgtt = (float)tottt / n;

printf(“\n\nAverage waiting time: %.2f”, avgwt);


printf(“\nAverage turnaround time: %.2f”, avgtt);
printf(“\n\nGantt Chart:”);

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


{
printf(“_”);
}
printf(“\n|”);

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


{
for (int j = 0; j < pr[i].tt; j++)
{
printf(“ “);
}
printf(“P%d|”, pr[i].pro);
}
printf(“\n”);
return 0;
}
OUTPUT:
Round robin scheduling
-----------------------------
Enter the no. of process: 3
Enter the time slice: 4
Process no: 1
Enter The Burst time:8
Process no: 2
Enter The Burst time:5
Process no: 3
Enter The Burst time:6

Process no: Burst time: Waiting time: Turn around time:


…………. ……….. …………. ……………
1 8 4 12
2 5 8 13
3 6 9 15

Average waiting time: 7.00


Average turnaround time: 13.33

Grantt Chart:
_______________
|P1 P2 P3|
IMPLEMENTATION OF SCHEDULING ALGORITHM (CPU)
(c)PRIORITY SCHEDULING

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>

#define MAX 10

struct process
{
int pro;
int brt;
int tt;
int wt;
int priority;
} pr[MAX];

// Function to sort the processes based on priority


void sortProcessesByPriority(struct process pr[], int n)
{
struct process temp;
for (int i = 1; i <= n; i++)
{
for (int j = i + 1; j <= n; j++)
{
if (pr[i].priority > pr[j].priority)
{
temp = pr[i];
pr[i] = pr[j];
pr[j] = temp;
}
}
}
}

int main()
{
int i, n, totwt = 0, tottt = 0, prevtt;
float avgwt, avgtt;

printf(“\n\tPriority Scheduling”);
printf(“\n---------------------------------“);
printf(“\nEnter the number of processes: “);
scanf(“%d”, &n);

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


{
pr[i].pro = i;
printf(“\nProcess no: %d”, pr[i].pro);
printf(“\nEnter the burst time: “);
scanf(“%d”, &pr[i].brt);
printf(“Enter the priority: “);
scanf(“%d”, &pr[i].priority);
}

// Sort processes based on priority


sortProcessesByPriority(pr, n);

prevtt = 0;
for (i = 1; i <= n; i++)
{
pr[i].wt = prevtt;
pr[i].tt = pr[i].wt + pr[i].brt;
prevtt = pr[i].tt;
}

printf(“\nProcess no:\tBurst time:\tPriority:\tWaiting time:\tTurn around


time:”);
printf(“\n……..\t……….\t……..\t…………\t…………..”);

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


{
printf(“\n%d\t\t%d\t\t%d\t\t%d\t\t%d”, pr[i].pro, pr[i].brt,
pr[i].priority, pr[i].wt, pr[i].tt);
totwt += pr[i].wt;
tottt += pr[i].tt;
}

avgwt = (float)totwt / n;
avgtt = (float)tottt / n;

printf(“\n\nAverage waiting time: %.2f”, avgwt);


printf(“\nAverage turnaround time: %.2f”, avgtt);
printf(“\n\n”);

for (i = 0; i <= pr[n].tt; i++)


{
printf(“.”);
}
printf(“\n”);

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


{
printf(“%d”, pr[i].wt);
for (int j = 0; j < pr[i].brt; j++)
{
printf(“ “);
}
pintf(“%d”, pr[i].tt);
}

printf(“\n”);
for (i = 0; i <= pr[n].tt; i++)
{
printf(“_”);
}
printf(“\n”);

return 0;
}
OUTPUT:
Priority scheduling
-------------------------
Enter the number of processes: 3
Process no: 1
Enter the burst time: 4
Enter the priority: 2
Process no: 2
Enter the burst time: 3
Enter the priority: 1
Process no: 3
Enter the burst time: 5
Enter the priority: 3
Process no: Burst time: Priority: Waiting time: Turn around time:
………… ………. …….. …………… …………..
2 3 1 0 3
1 4 2 3 7
3 5 3 7 12
Average waiting time: 3.33
Average turnaround time: 7.33
……………………..
0 3 7 12
IMPLEMENTATION OF SCHEDULING ALGORITHM (DISK)
(a) C-SCAN ALGORiTHM

PROGRAM CODE:
#include <stdio.h>
#include <math.h>
#define CYMAX 199

int main()
{
int i, j, req, tmov = 0, cp, np, cpo, npo, cyp[20], temp;
printf(“\n\t\tC-SCAN ALGORiTHM\n”);
printf(“\nEnter the number of requests: “);
scanf(“%d”, &req);
printf(“\nEnter the current head position: “);
scanf(“%d”, &cpo);
printf(“\nEnter the elements of the request:\n”);
cyp[0] = cpo;
for (i = 1; i <= req; i++)
{
scanf(“%d”, &cyp[i]);
}
for (i = 0; i <= req; i++)
{
for (j = 0; j < req – i; j++)
{
if (cyp[j] > cyp[j + 1])
{
temp = cyp[i];
cyp[j] = cyp[j + 1];
cyp[j + 1] = temp;
}
}
}
cp = 0;
while (cp <= req)
{
if (cyp[cp] == cpo) break;
cp++;
}
i = 0;
j = cp;
cpo = cyp[cp];
do
{
if (cpo == cyp[req])
{
npo = CYMAX;
cp = -1;
}
else
{
npo = cyp[++cp];
}
printf(“Moves from %d to %d with %d\n”, cpo, npo, abs(cpo –
npo));
tmov += abs(cpo – npo);
cpo = npo;

} while (cp != j – 1);


printf(“Total tracks displaced: %d\n”, tmov);
return 0;
}
OUTPUT:
C-SCAN ALGORITHM
Enter the number of requests: 8
Enter the current head position: 50
Enter the elements of the request:
82 170 43 140 24 16 190 10

Moves from 50 to 82 with 32


Moves from 82 to 140 with 58
Moves from 140 to 170 with 30
Moves from 170 to 190 with 20
Moves from 190 to 199 with 9
Moves from 199 to 0 with 199
Moves from 0 to 10 with 10
Moves from 10 to 16 with 6
Moves from 16 to 24 with 8
Moves from 24 to 43 with 19

Total tracks displaced: 391


IMPLEMENTATION OF BASIC MEMORY MANGEMENT SCHEME
(b)BEST FIT

PROGRAM CODE:
#include <stdio.h>
int main()
{
int m[20], p[20], i, j, np, nm, pos, min;
printf(“\t\t** BEST FiT **\n”);
printf(“Enter the number of processes: “);
scanf(“%d”, &np);
for (i = 0; i < np; i++) {
printf(“Enter the size of process %d: “, i + 1);
scanf(“%d”, &p[i]);
}
printf(“\nEnter the number of memory blocks: “);
scanf(“%d”, &nm);
for (i = 0; i < nm; i++){
printf(“Enter the size of block %d: “, i + 1);
scanf(“%d”, &m[i]);
}
for (i = 0; i < np; i++)
{
min = 9999;
pos = -1;
for (j = 0; j < nm; j++)
{
if (m[j] >= p[i] && m[j] < min)
{
min = m[j];
pos = j;
}
}
if (pos != -1)
{
printf(“\nThe process %d is allocated to block %d\n”, i
+ 1, pos + 1);
m[pos] -= p[i];
p[i] = -1; // Mark this process as allocated
}
}
for (i = 0; i < np; i++)
{
if (p[i] != -1)
printf(“The process %d is not allocated\n”, i + 1);
}

return 0;
}
OUTPUT:
** BEST FIT **
Enter the number of processes: 3
Enter the size of process 1: 212
Enter the size of process 2: 417
Enter the size of process 3: 112

Enter the number of memory blocks: 5


Enter the size of block 1: 100
Enter the size of block 2: 500
Enter the size of block 3: 200
Enter the size of block 4: 300
Enter the size of block 5: 600

The process 1 is allocated to block 4


The process 2 is allocated to block 5
The process 3 is allocated to block 3
IMPLEMENTATION OF BASIC MEMORY MANGEMENT SCHEME
(a)FIRST IN FIRST OUT

PROGRAM CODE:
#include <stdio.h>
int nf, ne, hit = 0, miss = 0, ref[50], fr[50];
void getdata();
void FiFO();
int search(int item);
void getdata()
{
int i;
printf(“\nEnter the number of frames: “);
scanf(“%d”, &nf);
printf(“\nEnter the number of elements in the reference string: “);
scanf(“%d”, &ne);
printf(“Enter the reference string:\n”);
for (i = 0; i < ne; i++)
{
scanf(“%d”, &ref[i]);
}
}
void FiFO()
{
int i, j, found = 0, rear = -1;
for (i = 0; i < nf; i++)
{
fr[i] = -1;
}
for (i = 0; i < ne; i++)
{
printf(“\nThe number to be inserted: %d\n”, ref[i]);
found = search(ref[i]);
if (found == 0)
{
miss++;
if (rear == nf – 1)
{
rear = -1;
}
rear++;
fr[rear] = ref[i];
}
else
{
hit++;
}
printf(“Frames: “);
for (j = 0; j < nf; j++)
{
if (fr[j] != -1)
{
printf(“%d “, fr[j]);
}
else
{
printf(“- “);
}
}
printf(“\n”);
}
printf(“\nNumber of page faults = %d\n”, miss);
printf(“Number of hits = %d\n”, hit);
}
int search(int item)
{
int i;
for (i = 0; i < nf; i++)
{
if (fr[i] == item)
return 1;
}
return 0;
}
int main()
{
printf(“\n\t\tFIFO PAGE REPLACEMENT\n”);
getdata();
printf(“\t\tFIFO PAGE REPLACEMENT\n”);
FiFO();
return 0;
}
OUTPUT:
FIFO PAGE REPLACEMENT
Enter the number of frames: 3
Enter the number of elements in the reference string: 8
Enter the reference string:
12341251
The number to be inserted: 1
Frames: 1 - -
The number to be inserted: 2
Frames: 1 2 -
The number to be inserted: 3
Frames: 1 2 3
The number to be inserted: 4
Frames: 4 2 3
The number to be inserted: 1
Frames: 4 1 3
The number to be inserted: 2
Frames: 4 1 2
The number to be inserted: 5
Frames: 5 1 2
The number to be inserted: 1
Frames: 5 1 2
Number of page faults = 6
Number of hits = 2
IMPLEMENTATION OF SYNCHRONISATION USING SEMAPHORE
(a)DINNING PHILOSOPHERS

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_PHiLOSOPHERS 5
pthread_mutex_t forks[NUM_PHILOSOPHERS];
pthread_t philosophers[NUM_PHILOSOPHERS]
void* philosopher(void* num)
{
int id = *(int*)num;
int left_fork = id;
int right_fork = (id + 1) % NUM_PHILOSOPHERS;
while (1) {
printf(“Philosopher %d is thinking.\n”, id);
sleep(1);
pthread_mutex_lock(&forks[left_fork]);
printf(“Philosopher %d picked up left fork %d.\n”, id, left_fork);
// Pick up right fork
pthread_mutex_lock(&forks[right_fork]);
printf(“Philosopher %d picked up right fork %d.\n”, id,
right_fork);
printf(“Philosopher %d is eating.\n”, id);
sleep(1);
pthread_mutex_unlock(&forks[right_fork]);
printf(“Philosopher %d put down right fork %d.\n”, id,
right_fork);
pthread_mutex_unlock(&forks[left_fork]);
printf(“Philosopher %d put down left fork %d.\n”, id, left_fork);
}
}
int main()
{
int ids[NUM_PHILOSOPHERS];
for (int i = 0; i < NUM_PHILOSOPHERS; i++)
pthread_mutex_init(&forks[i], NULL);
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
ids[i] = i;
pthread_create(&philosophers[i], NULL, philosopher, &ids[i]);
}
for (int i = 0; i < NUM_PHILOSOPHERS; i++)
pthread_join(philosophers[i], NULL);
for (int i = 0; i < NUM_PHILOSOPHERS; i++)
pthread_mutex_destroy(&forks[i]);
return 0;
}
OUTPUT:
Philosopher 0 is thinking.
Philosopher 1 is thinking.
Philosopher 2 is thinking.
Philosopher 3 is thinking.
Philosopher 4 is thinking.
Philosopher 0 picked up left fork 0.
Philosopher 0 picked up right fork 1.
Philosopher 0 is eating.
Philosopher 1 picked up left fork 1.
Philosopher 2 picked up left fork 2.
Philosopher 3 picked up left fork 3.
Philosopher 4 picked up left fork 4.
Philosopher 0 put down right fork 1.
Philosopher 0 put down left fork 0.
Philosopher 0 is thinking.
Philosopher 1 picked up right fork 2.
Philosopher 1 is eating.
Philosopher 1 put down right fork 2.
Philosopher 1 put down left fork 1.
Philosopher 1 is thinking.
Philosopher 2 picked up right fork 3.
Philosopher 2 is eating.
Philosopher 2 put down right fork 3.
Philosopher 2 put down left fork 2.
Philosopher 2 is thinking.
Philosopher 3 picked up right fork 4.
Philosopher 3 is eating.
Philosopher 3 put down right fork 4.
Philosopher 3 put down left fork 3.
Philosopher 3 is thinking.
Philosopher 4 picked up right fork 0.
Philosopher 4 is eating.
Philosopher 4 put down right fork 0.
Philosopher 4 put down left fork 4.
Philosopher 4 is thinking.

IMPLEMENTATION OF VIRTUAL MEMORY MANGEMENT
(a)LEAST RECENTLY USED

PROGRAM CODE:
#include <stdio.h>
int nf, i, ne, miss = 0, ref[50], fr[15];
void getdata()
{
printf(“\nEnter the number of frames: “);
scanf(“%d”, &nf);
printf(“\nEnter the number of elements in the reference string: “);
scanf(“%d”, &ne);
printf(“\nEnter the reference string:\n”);
for (i = 0; i < ne; i++)
scanf(“%d”, &ref[i]);
}
void lru()
{
int check, j, k, count = 0, index[15];
printf(“\nSimulation of LRU Page Replacement Technique!.....\n”);
for (i = 0; i < nf; i++)
fr[i] = -1;
for (i = 0; i < ne; i++)
{
check = 0;
for (j = 0; j < nf; j++)
{
if (fr[j] == ref[i])
{
check = 1;
break;
}
}
if (check == 0)
{
miss++;
if (count < nf)
{
fr[count++] = ref[i];
}
else
{
for (j = 0; j < nf; j++)
index[j] = 0;
for (j = i – 1, k = 1; k <= nf – 1; j--, k++)
{
for (int m = 0; m < nf; m++)
{
if (fr[m] == ref[j])
{
index[m] = 1;
}
}
}
for (j = 0; j < nf; j++)
{
if (index[j] == 0)
{
fr[j] = ref[i];
break;
}
}
}
}
for (j = 0; j < nf; j++)
{
if (fr[j] != -1)
printf(“%d\t”, fr[j]);
else
printf(“-\t”);
}
printf(“\n”);
}
printf(“\nNumber of page faults: %d\n”, miss);
}
int main()
{
printf(“\n\t\tLRU PAGE REPLACEMENT\n”);
getdata();
lru();
return 0;
}
OUTPUT:
LRU PAGE REPLACEMENT

Enter the number of frames: 3


Enter the number of elements in the reference string: 12
Enter the reference string:
701203042303
Simulation of LRU Page Replacement Technique!.....

7 - -
7 0 -
7 0 1
2 0 1
2 0 1
2 3 1
2 3 0
4 3 0
4 2 0
4 2 3
0 2 3
0 2 3

Number of page faults: 10


IMPLEMENTATION OF VIRTUAL MEMORY MANGEMENT
(c)OPTIMAL PAGE REPLACEMENT POLICY

PROGRAM CODE:
#include <stdio.h>
int findOptimal(int pages[], int n, int frame[], int f, int index)
{
int pos = -1, farthest = index;
for (int i = 0; i < f; i++)
{
int j;
for (j = index; j < n; j++)
{
if (frame[i] == pages[j])
{
if (j > farthest)
{
farthest = j;
pos = i;
}
break;
}
}
if (j == n)
{
return i;
}
}
return (pos == -1) ? 0 : pos;
}
void optimalPageReplacement(int pages[], int n, int f)
{
int frame[f];
int hit = 0, miss = 0, index = 0;
for (int i = 0; i < f; i++)
{
frame[i] = -1;
}
for (int i = 0; i < n; i++)
{
int found = 0;
for (int j = 0; j < f; j++)
{
if (frame[j] == pages[i])
{
found = 1;
hit++;
break;
}
}
if (!found)
{
if (index < f)
{
frame[index++] = pages[i];
}
else
{
int pos = findOptimal(pages, n, frame, f, i + 1);
frame[pos] = pages[i];
}
miss++;
}
printf(“Frame state after accessing page %d: “, pages[i]);
for (int j = 0; j < f; j++)
{
if (frame[j] != -1)
{
printf(“%d “, frame[j]);
}
else
{
printf(“- “);
}
}
printf(“\n”);
}
printf(“Total hits: %d\n”, hit);
printf(“Total misses: %d\n”, miss);
}
int main()
{
int n, f;
printf(“Enter the number of pages: “);
scanf(“%d”, &n);
int pages[n];
printf(“Enter the page reference sequence: “);
for (int i = 0; i < n; i++)
{
scanf(“%d”, &pages[i]);
}
printf(“Enter the number of frames: “);
scanf(“%d”, &f);
optimalPageReplacement(pages, n, f);
return 0;
}
OUTPUT:
Enter the number of pages: 8
Enter the page reference sequence: 7 0 1 2 0 3 0 4
Enter the number of frames: 3
Frame state after accessing page 7: 7 - -
Frame state after accessing page 0: 7 0 -
Frame state after accessing page 1: 7 0 1
Frame state after accessing page 2: 2 0 1
Frame state after accessing page 0: 2 0 1
Frame state after accessing page 3: 2 0 3
Frame state after accessing page 0: 2 0 3
Frame state after accessing page 4: 4 0 3
Total hits: 2
Total misses: 6
IMPLEMENTATION OF SYNCHRONISATION PROBLEM USING
SEMAPHORE
(c)PRODUCER AND CONSUMER

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
// Global variables
int mutex = 1, full = 0, empty = 5; // assuming buffer size is 5
int x = 0;
// Producer function
void producer()
{
--mutex;
++full;
--empty;
++x;
printf(“The producer produces an item: %d\n”, x);
++mutex;
}

// Consumer function
void consumer()
{
--mutex;
--full;
++empty;
printf(“The consumer consumes an item: %d\n”, x);
--x;
++mutex;
}

int main()
{
int n, i;
while (1)
{
printf(“Enter 1 for Producer, 2 for Consumer, 3 to Exit: “);
scanf(“%d”, &n);

switch (n)
{
case 1:
if (mutex == 1 && empty != 0)
{
producer();
}
else
{
printf(“Buffer is full\n”);
}
break;
case 2:
if (mutex == 1 && full != 0)
{
consumer();
}
else
{
printf(“Buffer is empty\n”);
}
break;
case 3:
exit(0);
default:
printf(“Invalid input\n”);
break;
}
}
return 0;
}
OUTPUT:
Enter 1 for Producer, 2 for Consumer, 3 to Exit: 1
The producer produces an item: 1
Enter 1 for Producer, 2 for Consumer, 3 to Exit: 1
The producer produces an item: 2
Enter 1 for Producer, 2 for Consumer, 3 to Exit: 2
The consumer consumes an item: 2
Enter 1 for Producer, 2 for Consumer, 3 to Exit: 3
IMPLEMENTATION OF SYNCHRONISATION USING SEMAPHORE
(b)DEADLOCK AVOIDANCE USING BANKER’S ALGORITHM

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>

void matrix_get(int a[5][5], int p, int r);

int main()
{
int max[5][5], all[5][5], total[1][5];
int avail[1][5], f[5], need[5][5], state[5];
int p, r, i, j, k = 0, ch, ch1, c;
printf(“\t\tDEADLOCK-BANKER’S ALGORITHM\n”);
printf(“Enter the number of processes: “);
scanf(“%d”, &p);
printf(“Enter the number of resource types: “);
scanf(“%d”, &r);
printf(“Enter the max matrix:\n”);
matrix_get(max, p, r);
printf(“Enter the allocation matrix:\n”);
matrix_get(all, p, r);
printf(“Enter the resource present:\n”);
matrix_get(total, 1, r);
for (i = 0; i < r; i++)
{
for (j = 0; j < p; j++)
{
if (max[j][i] > total[0][i] || all[j][i] > total[0][i])
{
printf(“\ninput is greater than total resource
present\n”);
exit(0);
}
}
}
for (i = 0; i < r; i++)
{
int s = total[0][i];
for (j = 0; j < p; j++)
{
s -= all[j][i];
}
avail[0][i] = s;
}
printf(“\nAvailable matrix:\n”);
for (i = 0; i < r; i++)
{
printf(“%d\t”, avail[0][i]);
}
printf(“\nNeed matrix:\n”);
for (i = 0; i < p; i++)
{
f[i] = 0;
for (j = 0; j < r; j++)
{
need[i][j] = max[i][j] - all[i][j];
if (need[i][j] < 0)
need[i][j] = 0;
printf(“%d\t”, need[i][j]);
}
printf(“\n”);
}
ch = p;
while (ch > 0)
{
ch1 = ch;
for (i = 0; i < p; i++)
{
if (f[i] == 0)
{
c = 0;
for (j = 0; j < r; j++)
{
if (need[i][j] <= avail[0][j])
c++;
}
if (c == r)
{
f[i] = 1;
state[k++] = i;
ch--;
for (j = 0; j < r; j++)
{
avail[0][j] += all[i][j];
need[i][j] = 0;
}
}
}
}

if (ch == p)
{
printf(“\nAlready deadlock occurred\n”);
exit(0);
}
if (ch1 == ch)
{
printf(“\nAllocation deadlock occurred\n”);
exit(0);
}
}
printf(“\n\nSafe State is: { “);
for (i = 0; i < p; i++)
printf(“P%d “, state[i]);
printf(“}\n”);
return 0;
}

void matrix_get(int a[5][5], int p, int r)


{
int i, j;
for (i = 0; i < p; i++)
{
for (j = 0; j < r; j++)
scanf(“%d”, &a[i][j]);
}
}
OUTPUT:
DEADLOCK-BANKER’S ALGORITHM
Enter the number of processes: 3
Enter the number of resource types: 3
Enter the max matrix:
123
456
789
Enter the allocation matrix:
010
200
302
Enter the resource present:
10 5 7

Available matrix:
5 4 5
Need matrix:
1 1 3
2 5 6
4 8 7

Safe State is: { P0 P1 P2 }


IMPLEMENTATION OF SCHEDULING ALGORITHM (CPU)
(a)FIRST COME FIRST SERVE

PROGRAM CODE:
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
Struct process
{
pro, brt, tt, wt;
} pr[MAX];

int main()
{
int i, n, totwt = 0, tottt = 0, prevtt;
float avgwt, avgtt;
Printf(“\n\tFirst Come First Serve”);
Printf(“\n---------------------------------“);
Printf(“\nEnter the number of processes: “);
Scanf(“%d”, &n);
for (i = 1; i <= n; i++)
{
pr[i].pro = i;
Printf(“\nProcess no: %d”, pr[i].pro);
Printf(“\nEnter the burst time: “);
Scanf(“%d”, &pr[i].brt);
}
Prevtt = 0;
for (i = 1; i <= n; i++)
{
pr[i].wt = prevtt;
pr[i].tt = pr[i].wt + pr[i].brt;
prevtt = pr[i].tt;
}
Printf(“\nProcess no:\tBurst time:\tWaiting time:\tTurn around time:”);
Printf(“\n……….\t……….\t……….\t……….”);
for (i = 1; i <= n; i++)
{
Printf(“\n%d\t\t%d\t\t%d\t\t%d”, pr[i].pro, pr[i].brt, pr[i].wt,
pr[i].tt);
totwt += pr[i].wt;
tottt += pr[i].tt;
}
avgwt = (float) totwt / n;
avgtt = (float) tottt / n;
Printf(“\n\nAverage waiting time: %.2f”, avgwt);
Printf(“\nAverage turnaround time: %.2f”, avgtt);
Printf(“\n\n”);
for (i = 0; i <= pr[n].tt; i++)
{
Printf(“.”);
}
Printf(“\n”);
for (i = 1; i <= n; i++)
{
Printf(“%d”, pr[i].wt);
for (int j = 0; j < pr[i].brt; j++)
{
Printf(“ “);
}
Printf(“%d”, pr[i].tt);
}
Printf(“\n”);
for (i = 0; i <= pr[n].tt; i++)
{
Printf(“_”);
}
Printf(“\n”);
return 0;
}
OUTPUT:
First come first serve
--------------------------
Process no: 1
Enter the burst time: 4
Process no: 2
Enter the burst time: 5
Process no: 3
Enter the burst time: 6

Process no: Burst time: Waiting time: Turn around time:


………. ………. ………. ……….
1 4 0 4
2 5 4 9
3 6 9 15

Average waiting time: 4.33


Average turnaround time: 9.33
…………….
0 4 9 15
IMPLEMENTATION OF SHELL PROGRAMMING
(d)STAT() SYSTEM CALL

PROGRAM CODE:
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if (argc != 2){
Fprintf(stderr, “usage: %s <filename>\n”, argv[0]);
return 1;
}
Struct stat filestat;
if (stat(argv[1], &filestat) < 0) {
perror(“stat”);
return 1;
}
Printf(“File: %s\n”, argv[1]);
Printf(“Size: %ld bytes\n”, filestat.st_size);
Printf(“Mode: %o\n”, filestat.st_mode);
Printf(“Owner: %d\n”, filestat.st_uid);
Printf(“Group: %d\n”, filestat.st_gid);
return 0;
}
OUTPUT :
$ ./a.out testfile.txt
File: testfile.txt
Size: 1024 bytes
Mode: 100644
Owner: 1000
Group: 1000
IMPLEMENTATION OF SHELL PROGRAMMING
(e)SIMULATION OF GREP()

PROGRAM CODE:
#include <stdio.h>
#include <string.h> // include this for the strcmp function
int main()
{
FILE *f;
char str[10], strf[10];
int flag = 0; // Corrected the variable declaration
printf(“Enter the pattern: “);
scanf(“%s”, str);
f = fopen(“CSE.txt”, “r”);
if (f == NULL)
{
printf(“Error opening file\n”);
return 1;
}
while (fscanf(f, “%s”, strf) != EOF)
{
if (strcmp(str, strf) == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
printf(“The pattern is found\n”);
else
printf(“The pattern is not found\n”);
fclose(f);
return 0;
}
OUTPUT:
Enter the pattern : HELLO WORLD
The pattern is found
Enter the pattern: HELLO
The pattern is not found
IMPLEMENTATION OF FILE SYSTEM
(a)SIMPLE FILE SYSTEM
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>

void createFile(const char *filename)


{
FILE *file = fopen(filename, “w”);
if (file == NULL)
{
printf(“Could not create file %s\n”, filename);
return;
}
printf(“File %s created successfully\n”, filename);
fclose(file);
}

void writeFile(const char *filename, const char *content)


{
FILE *file = fopen(filename, “a”);
if (file == NULL)
{
printf(“Could not open file %s for writing\n”, filename);
return;
}
fprintf(file, “%s\n”, content);
printf(“Content written to file %s successfully\n”, filename);
fclose(file);
}

void readFile(const char *filename)


{
FILE *file = fopen(filename, “r”);
if (file == NULL)
{
printf(“Could not open file %s for reading\n”, filename);
return;
}
char ch;
printf(“Content of file %s:\n”, filename);
while ((ch = fgetc(file)) != EOF)
{
putchar(ch);
}
fclose(file);
}
void deleteFile(const char *filename)
{
if (remove(filename) == 0)
{
printf(“File %s deleted successfully\n”, filename);
}
else
{
printf(“Could not delete file %s\n”, filename);
}
}

int main()
{
const char *filename = “example.txt”;

createFile(filename);
writeFile(filename, “Hello, world!”);
writeFile(filename, “This is a simple file system implementation in C.”);
readFile(filename);
deleteFile(filename);

return 0;
}
OUTPUT:
File example.txt created successfully
Content written to file example.txt successfully
Content written to file example.txt successfully
Content of file example.txt:
Hello, world!
This is a simple file system implementation in C.
File example.txt deleted successfully
IMPLEMENTATION OF VIRTUAL MEMORY MANGEMENT
(b)FIRST IN FIRST OUT

PROGRAM CODE:
#include <stdio.h>
void fifoPageReplacement(int pages[], int n, int frames[], int f)
{
int hit = 0, miss = 0, index = 0;
for (int i = 0; i < f; i++)
{
frames[i] = -1;
}
for (int i = 0; i < n; i++)
{
int found = 0;
for (int j = 0; j < f; j++)
{
if (frames[j] == pages[i])
{
found = 1;
hit++;
break;
}
}
if (!found)
{
frames[index] = pages[i];
index = (index + 1) % f;
miss++;
}

printf(“Frame state after accessing page %d: “, pages[i]);


for (int j = 0; j < f; j++)
{
if (frames[j] != -1)
{
printf(“%d “, frames[j]);
}
else
{
printf(“- “);
}
}
printf(“\n”);
}

printf(“Total hits: %d\n”, hit);


printf(“Total misses: %d\n”, miss);
}

int main()
{
int n, f;

printf(“Enter the number of pages: “);


scanf(“%d”, &n);

int pages[n];
printf(“Enter the page reference sequence: “);
for (int i = 0; i < n; i++)
{
scanf(“%d”, &pages[i]);
}

printf(“Enter the number of frames: “);


scanf(“%d”, &f);

int frames[f];
fifoPageReplacement(pages, n, frames, f);
return 0;
}
OUTPUT:
Enter the number of pages: 8
Enter the page reference sequence: 1 3 0 3 5 6 3 1
Enter the number of frames: 3
Frame state after accessing page 1: 1 - -
Frame state after accessing page 3: 1 3 –
Frame state after accessing page 0: 1 3 0
Frame state after accessing page 3: 1 3 0
Frame state after accessing page 5: 5 3 0
Frame state after accessing page 6: 5 6 0
Frame state after accessing page 3: 5 6 3
Frame state after accessing page 1: 1 6 3
Total hits: 1
Total misses: 7
IMPLEMENTATION OF SHELL PROGRAMMING
(c)EXECVP() SYSTEM CALL

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAX_ARGS 10
int main()
{
char command[100], *args[MAX_ARGS];
int status;
printf(“Enter the command: “);
fgets(command, sizeof(command), stdin);
if (command[strlen(command) – 1] == ‘\n’)
command[strlen(command) – 1] = ‘\0’;
char *token = strtok(command, “ “);
int i = 0;
while (token != NULL && i < MAX_ARGS – 1)
{
args[i] = token;
token = strtok(NULL, “ “);
i++;
}
args[i] = NULL;
pid_t pid = fork();
if (pid < 0)
{
perror(“Fork failed”);
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
execvp(args[0], args);
perror(“execvp failed”);
exit(EXIT_FAILURE);
}
else
{
waitpid(pid, &status, 0);
if (WIFEXITED(status))
printf(“Child process exited with status %d\n”,
WEXITSTATUS(status));
}
return 0;
}
OUTPUT:
$ gcc -o program program.c
$ ./program
Enter the command: ls -l
Total 8
-rwxr-xr-x 1 user user 16384 Jun 14 10:00 program
-rw-r—r—1 user user 456 Jun 14 10:00 program.c
Child process exited with status 0
IMPLEMENTATION OF SHELL PROGRAMMING
(b)EXEC() SYSTEM CALL

PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
char *command = “ls”;
char *arg1 = “-l”;
char *arg2 = NULL;
pid_t pid = fork();
if (pid < 0)
{
printf(“fork failed\n”);
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
execlp(command, command, arg1, arg2, NULL);
printf(“execlp failed\n”);
exit(EXIT_FAILURE);
}
else
{
int status;
waitpid(pid, &status, 0);
if (WiFEXiTED(status))
{
printf(“Child process exited with status %d\n”,
WEXITSTATUS(status));
}
}
return 0;
}
OUTPUT:
Total 8
-rwxr-xr-x 1 user user 16384 Jun 14 10:00 program
-rw-r—r—1 user user 456 Jun 14 10:00 program.c
Child process exited with status 0
IMPLEMENTATION OF SHELL PROGRAMMING
(f)DIRENT SYSTEM CALL
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h> // include dirent.h for directory handling
int main(int argc, char *argv[]){
if (argc != 2){
fprintf(stderr, “usage: %s <directory>\n”, argv[0]);
return 1;
}
DIR *dir;
struct dirent *entry;
dir = opendir(argv[1]); // Corrected function name and parameter usage
if (dir == NULL){
perror(“opendir”);
return 1;
}
printf(“Contents of directory %s:\n”, argv[1]);
while ((entry = readdir(dir)) != NULL)
printf(“%s\n”, entry->d_name);
closedir(dir);
return 0;
}
OUTPUT:
$ ./a.out /home/user
Contents of directory /home/user:
File1.txt
File2.txt
Subdirectory
IMPLEMENTATION OF SHELL PROGRAMMING
(a)FORK() SYSTEM CALL

PROGRAM CODE:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
int pid, P1, P2;
pid = fork();
printf(“In after fork called\n”);
if (pid > 0) {
wait(NULL);
p1 = getpid();
printf(“In parent process, ID: %d\n”, P1);
}
else if (pid == 0) {
p2 = getpid();
printf(“In child process, ID: %d\n”, P2);
}
else if (pid == -1)
printf(“Error in fork creation\n”);
return 0;
}
OUTPUT:
In after fork called
In after fork called
In child process, ID: 12345
In parent process, ID: 12344
IMPLEMENTATION OF SCHEDULING ALGORITHM (CPU)
(b)SHORTEST JOB FIRST

PROGRAM CODE:
#include <stdio.h>

void findWaitingTime(int processes[], int n, int bt[], int wt[])


{
wt[0] = 0;

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


wt[i] = bt[i – 1] + wt[i – 1];
}

void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[])
{
for (int i = 0; i < n; i++)
tat[i] = bt[i] + wt[i];
}

void findAverageTime(int processes[], int n, int bt[])


{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(processes, n, bt, wt);
findTurnAroundTime(processes, n, bt, wt, tat);

printf(“Processes Burst time Waiting time Turnaround time\n”);

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


{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf(“ %d “, (i + 1));
printf(“ %d “, bt[i]);
printf(“ %d”, wt[i]);
printf(“ %d\n”, tat[i]);
}

printf(“Average waiting time = %.2f\n”, (float)total_wt / (float)n);


printf(“Average turnaround time = %.2f\n”, (float)total_tat / (float)n);
}

void sortProcesses(int processes[], int n, int bt[])


{
for (int i = 0; i < n – 1; i++)
{
for (int j = 0; j < n – i – 1; j++)
{
if (bt[j] > bt[j + 1])
{
int temp = bt[j];
bt[j] = bt[j + 1];
bt[j + 1] = temp;

temp = processes[j];
processes[j] = processes[j + 1];
processes[j + 1] = temp;
}
}
}
}

int main()
{
int processes[] = {1, 2, 3, 4, 5};
int n = sizeof processes / sizeof processes[0];
int burst_time[] = {6, 2, 8, 3, 4};
sortProcesses(processes, n, burst_time);
findAverageTime(processes, n, burst_time);
return 0;
}
OUTPUT:
Processes Burst time Waiting time Turnaround time
1 2 0 2
2 3 2 5
3 4 5 9
4 6 9 15
5 8 15 23
Average waiting time = 6.20
Average turnaround time = 10.80
First-In-First-Out (FIFO) page replacement algorithm.

1. Initialize:
- Define the number of pages (n), the number of frames (f), and the page
reference sequence (pages).
- Initialize the frame array (frames) with -1.
2. FIFO page replacement:
- For each page in the reference sequence:
- Check if the page is already in the frame array (hit).
- If not, replace the oldest page in the frame array with the current page
(miss).
- Update the frame array and increment the hit or miss counter accordingly.
3. Print frame state:
- Print the frame array after each page access.
4. Print statistics:
- Print the total hits and misses.

1
Shortest Job First (SJF) scheduling algorithm.

1. Initialize:
- Define the number of processes (n) and their burst times (bt).
- Initialize the process array (processes) and the burst time array (bt).
2. Sort processes by burst time:
- Use a bubble sort algorithm to sort the processes in ascending order of burst
time.
3. Calculate waiting time:
- Initialize the waiting time array (wt) with 0.
- For each process, calculate its waiting time as the sum of the burst times of
all previous processes.
4. Calculate turnaround time:
- For each process, calculate its turnaround time as the sum of its burst time
and waiting time.
5. Calculate average waiting time and average turnaround time:
- Sum up the waiting times and turnaround times of all processes.
- Calculate the average waiting time and average turnaround time by dividing
the sums by the number of processes.
6. Print results:
- Print the process number, burst time, waiting time, and turnaround time for
each process.
- Print the average waiting time and average turnaround time.

2
Simple Demonstration Of The Producer-consumer Problem Using Mutex
Locks For Synchronization.

1. Initialize:

- Set the global variables:

- mutex (mutex lock) to 1 (unlocked)

- full (number of full buffers) to 0

- empty (number of empty buffers) to 5 (assuming a buffer size of 5)

- x (produced/consumed item) to 0

2. Producer Function:

- Decrement the mutex lock (mutex--)

- Increment the full buffer count (full++)

- Decrement the empty buffer count (empty--)

- Increment the produced item count (x++)

- Print a message indicating production

- Increment the mutex lock (mutex++)

3. Consumer Function:

- Decrement the mutex lock (mutex--)

- Decrement the full buffer count (full--)

- Increment the empty buffer count (empty++)

- Print a message indicating consumption

- Decrement the consumed item count (x--)

- Increment the mutex lock (mutex++)

4. Main Loop:

- Prompt the user to enter a choice (1 for Producer, 2 for Consumer, 3 to Exit)

- Read the user input (n)

- Switch based on the user input:

- Case 1 (Producer):

3
- Check if the mutex is unlocked (mutex == 1) and the buffer is not full (empty != 0)

- If true, call the producer function

- Otherwise, print a message indicating the buffer is full

- Case 2 (Consumer):

- Check if the mutex is unlocked (mutex == 1) and the buffer is not empty (full != 0)

- If true, call the consumer function

- Otherwise, print a message indicating the buffer is empty

- Case 3 (Exit):

- Exit the program

- Default:

- Print an error message for invalid input.

4
Simple Simulation Of The Grep() Command

1. Initialize:

- Declare variables:

- str (to store the search pattern)

- strf (to store each word read from the file)

- flag (to indicate whether the pattern is found or not)

- Set flag to 0 (pattern not found)

2. Prompt the user to enter a search pattern

3. Open the file "CSE.txt" in read mode

- If the file cannot be opened, print an error message and exit

4. Read each word from the file using fscanf()

- Compare the read word (strf) with the search pattern (str) using strcmp()

- If the pattern is found (strcmp() returns 0), set flag to 1 and break out of the loop

5. Check the value of flag:

- If flag is 1, print "The pattern is found"

- Otherwise, print "The pattern is not found"

6. Close the file using fclose()

7. Exit the program.

5
Simple Demonstration Of The Execvp() System Call

1. Initialize:

- Define a character array (command) to store the user-input command.

- Define an array of pointers (args) to store the command arguments.

- Set the maximum number of arguments (MAX_ARGS) to 10.

2. Prompt the user to enter a command:

- Read the command using fgets() and store it in the command array.

- Remove the newline character at the end of the command, if present.

3. Tokenize the command:

- Use strtok() to split the command into individual arguments (tokens).

- Store each token in the args array.

- Set the last element of the args array to NULL to indicate the end of the argument
list.

4. Fork a new process:

- Use the fork() system call to create a new process.

- If fork() fails, print an error message and exit.

5. Child process:

- Execute the new program using execvp(), passing the command name and
arguments.

- If execvp() fails, print an error message and exit.

6. Parent process:

- Wait for the child process to finish using waitpid().

- Check the exit status of the child process using WIFEXITED() and print the exit status
if it exited normal
6
First-in-first-out (FIFO) Page Replacement Algorithm.

1. Get data:

- Read the number of frames (nf) and the number of elements in the reference string
(ne) from the user.

- Read the reference string into an array (ref).

2. Initialize:

- Set the hit and miss counters to 0.

- Initialize the frame array (fr) with -1 to indicate empty frames.

3. FIFO algorithm:

- Iterate through the reference string:

- For each element, check if it's already in the frame array using the search function.

- If not found (miss), increment the miss counter and insert the element into the
next available frame.

- If found (hit), increment the hit counter.

- Print the current state of the frames after each insertion.

4. Search function:

- Iterate through the frame array to find the given element.

- Return 1 if found, 0 otherwise.

5. Print statistics:

- Print the total number of page faults (misses) and hits.

7
C-SCAN (Circular SCAN) Algorithm

1. Initialize:

- Define the maximum cylinder value (CYMAX) as 199.

- Read the number of requests (req) from the user.

- Read the current head position (cpo) from the user.

- Read the request array (cyp) from the user.

2. Sort the request array in ascending order using a bubble sort algorithm.

3. Find the initial position of the head in the sorted request array.

4. Initialize the total movement (tmov) to 0.

5. Loop through the request array:

- If the head is at the last request, move to the maximum cylinder value (CYMAX).

- Otherwise, move to the next request in the sorted array.

- Calculate the absolute distance between the current head position and the next
request.

- Add the distance to the total movement (tmov).

- Update the head position to the next request.

6. Print the total tracks displaced (tmov).

8
Banker's Algorithm For Deadlock Avoidance.

1. Initialize:

- Read the number of processes (p) and resource types (r) from the user.

- Initialize matrices for max resources (max), allocated resources (all), total resources
(total), available resources (avail), need matrix (need), and a flag array (f) to keep track
of processes that have been allocated resources.

2. Input matrices:

- Read the max matrix, allocation matrix, and total resources from the user.

3. Check for invalid input:

- Verify that the max resources and allocated resources do not exceed the total
resources for each resource type.

4. Calculate available resources:

- Subtract allocated resources from total resources for each resource type.

5. Calculate need matrix:

- Subtract allocated resources from max resources for each process and resource
type.

6. Find a safe sequence:

- While there are still processes that need resources (ch > 0):

- Find a process that can be allocated resources without exceeding available


resources.

- Mark the process as allocated (f[I] = 1) and add it to the safe sequence (state).

- Update available resources by adding the allocated resources.

7. Check for deadlock:

- If no process can be allocated resources without exceeding available resources, a


deadlock has occurred.

8. Print the safe sequence:

- Print the safe sequence of processes that can be allocated resources without
causing a deadlock.

9
Simple Demonstration Of The Exec() System Call Using The
Execlp() Variant

1. Initialize:

- Define the command to execute (ls) and its arguments (-l).

- Set arg2 to NULL to indicate the end of the argument list.

2. Fork:

- Create a new process using the fork() system call.

- If fork() fails, print an error message and exit.

3. Child Process:

- If this is the child process (pid == 0), execute the ls command with the -l argument
using execlp().

- If execlp() fails, print an error message and exit.

4. Parent Process:

- If this is the parent process (pid > 0), wait for the child process to finish using
waitpid().

- Check the exit status of the child process using WIFEXITED() and print the exit status
if it exited normally.

5. Exit:

- Return 0 from the main function to indicate successful execution.

10
First-come-first-served (FCFS) Scheduling Algorithm.

1. Input:

- Prompt the user to enter the number of processes (n).

- Read the burst time for each process.

2. Initialize:

- Set the waiting time (wt) and turn-around time (tt) for each process to 0.

- Set the previous turn-around time (prevtt) to 0.

3. Calculate Waiting Time and Turn-Around Time:

- For each process, calculate the waiting time (wt) as the previous turn-around time
(prevtt).

- Calculate the turn-around time (tt) as the sum of the waiting time (wt) and burst time
(brt).

- Update the previous turn-around time (prevtt) with the current turn-around time (tt).

4. Print Process Information:

- Print the process number, burst time, waiting time, and turn-around time for each
process.

5. Calculate Average Waiting Time and Average Turn-Around Time:

- Calculate the total waiting time (totwt) and total turn-around time (tottt) by summing
up the waiting times and turn-around times of all processes.

- Calculate the average waiting time (avgwt) and average turn-around time (avgtt) by
dividing the total waiting time and total turn-around time by the number of processes
(n).

6. Print Average Times:

- Print the average waiting time and average turn-around time.

7. Print Gantt Chart:

- Print a Gantt chart representing the execution of processes.

11
Round Robin Scheduling Algorithm.

1. Initialize:

- Define the maximum number of processes (MAX) as 10.

- Declare a struct to represent a process, including its process number (pro), burst
time (brt), turn-around time (tt), waiting time (wt), and remaining time (remt).

2. Input:

- Read the number of processes (n) and time slice (ts) from the user.

- For each process, read its burst time and store it in the pr array.

3. Calculate total burst time:

- Calculate the total burst time (totbrt) by summing up the burst times of all
processes.

4. Schedule processes:

- While the total time (tott) is less than the total burst time (totbrt), schedule
processes in a round-robin manner.

- For each process, check if it has remaining time (remt). If it does, execute it for the
time slice (ts) or until its remaining time is 0.

- Update the total time (tott), waiting time (wt), and turn-around time (tt) for each
process.

5. Print results:

- Print the process number, burst time, waiting time, and turn-around time for each
process.

- Calculate the average waiting time (avgwt) and average turn-around time (avgtt) by
summing up the waiting times and turn-around times of all processes and dividing by
the number of processes (n).

6. Print Gantt chart:

- Print a Gantt chart representing the execution of processes.

12
Best Fit Algorithm

1. Initialize:

- Read the number of processes (np) and memory blocks (nm) from the user.

- Declare arrays to store process sizes (p) and memory block sizes (m).

2. Input process sizes:

- For each process, read its size from the user and store it in the p array.

3. Input memory block sizes:

- For each memory block, read its size from the user and store it in the m array.

4. Allocate processes to memory blocks:

- For each process, find the best-fit memory block that can accommodate it.

- If a suitable block is found, allocate the process to that block and update the block
size.

- Mark the process as allocated.

5. Print allocation results:

- For each process, print whether it was allocated to a memory block or not.

- If allocated, print the block number.

13
Priority Scheduling Algorithm.

1. Initialize:

- Define the maximum number of processes (MAX) as 10.

- Declare a struct to represent a process, including its process number (pro), burst
time (brt), turn-around time (tt), waiting time (wt), and priority.

2. Input:

- Read the number of processes (n) from the user.

- For each process, read its burst time and priority from the user and store them in the
pr array.

3. Sort processes by priority:

- Use a simple sorting algorithm (insertion sort) to sort the processes in ascending
order of priority.

4. Calculate waiting and turn-around times:

- Initialize a variable (prevtt) to keep track of the previous turn-around time.

- For each process, calculate its waiting time (wt) as the previous turn-around time
(prevtt).

- Calculate its turn-around time (tt) as the sum of its waiting time and burst time.

- Update the previous turn-around time (prevtt) with the current process's turn-
around time.

5. Print results:

- Print the process number, burst time, priority, waiting time, and turn-around time for
each process.

- Calculate the average waiting time (avgwt) and average turn-around time (avgtt) by
summing up the waiting times and turn-around times of all processes and dividing by
the number of processes (n).

6. Print Gantt chart:

- Print a Gantt chart representing the execution of processes.

14
Least Recently Used (LRU) Page Replacement Algorithm

1. Initialize:

- Define the number of frames (nf) and the number of elements in the reference string
(ne).

- Initialize the reference string (ref) and the frame array (fr) with -1.

2. Get data:

- Read the number of frames (nf) and the number of elements in the reference string
(ne) from the user.

- Read the reference string from the user.

3. LRU algorithm:

- For each element in the reference string:

- Check if the element is already in the frame array (fr).

- If not, increment the miss counter and:

- If the frame array is not full, add the element to the frame array.

- If the frame array is full, find the least recently used frame and replace it with the
current element.

- Print the final frame array.

4. Print statistics:

- Print the number of page faults (misses).

15
Optimal Page Replacement

1. Initialize:

- Define the number of pages (n), the number of frames (f), and the page reference
sequence (pages).

- Initialize the frame array (frame) with -1.

2. Find optimal page replacement:

- For each page in the reference sequence:

- Check if the page is already in the frame array (hit).

- If not, find the optimal page to replace:

- Find the page that will not be used for the longest time in the future (farthest).

- If no such page is found, replace the page that has not been used for the longest
time (least recently used).

- Update the frame array and increment the miss counter.

3. Print frame state:

- Print the frame array after each page access.

4. Print statistics:

- Print the total hits and misses.

16
First-in-first-out (FIFO)

1. Initialize:

- Define the number of pages (n), the number of frames (f), and the page reference
sequence (pages).

- Initialize the frame array (frames) with -1.

2. FIFO page replacement:

- For each page in the reference sequence:

- Check if the page is already in the frame array (hit).

- If not, replace the oldest page in the frame array with the current page (miss).

- Update the frame array and increment the hit or miss counter accordingly.

3. Print frame state:

- Print the frame array after each page access.

4. Print statistics:

- Print the total hits and misses.

17
Dining Philosophers Problem
1. Initialize:

- Create an array of mutex locks (forks) and philosopher threads.

- Initialize the mutex locks.

2. Philosopher Thread:

- Each philosopher thread represents a philosopher.

- The thread function takes an integer argument (id) representing the philosopher's ID.

3. Thinking:

- The philosopher thinks for a random time (simulated with sleep(1)).

4. Pick up Left Fork:

- The philosopher tries to lock the mutex corresponding to their left fork (forks[id]).

- If successful, they print a message indicating they've picked up the left fork.

5. Pick up Right Fork:

- The philosopher tries to lock the mutex corresponding to their right fork (forks[(id +
1) % NUM_PHILOSOPHERS]).

- If successful, they print a message indicating they've picked up the right fork.

6. Eating:

- The philosopher eats for a random time (simulated with sleep(1)).

7. Put down Right Fork:

- The philosopher unlocks the mutex corresponding to their right fork.

- They print a message indicating they've put down the right fork.

8. Put down Left Fork:

- The philosopher unlocks the mutex corresponding to their left fork.

- They print a message indicating they've put down the left fork.

9. Repeat:

- The philosopher repeats the thinking, eating, and putting down forks process
indefinitely.

18
10. Main Thread:

- Create and join all philosopher threads.

- Destroy the mutex locks.

19
Stat sytem call

20
Dir system call

21
Fork system call

22

You might also like