OSrec
OSrec
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;
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;
}
}
}
avgwt = (float)totwt / n;
avgtt = (float)tottt / n;
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];
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);
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;
}
avgwt = (float)totwt / n;
avgtt = (float)tottt / n;
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;
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
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
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
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>
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;
}
Available matrix:
5 4 5
Need matrix:
1 1 3
2 5 6
4 8 7
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
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>
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++;
}
int main()
{
int n, f;
int pages[n];
printf(“Enter the page reference sequence: “);
for (int i = 0; i < n; i++)
{
scanf(“%d”, &pages[i]);
}
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 findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[])
{
for (int i = 0; i < n; i++)
tat[i] = bt[i] + wt[i];
}
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:
- x (produced/consumed item) to 0
2. Producer Function:
3. Consumer Function:
4. Main Loop:
- Prompt the user to enter a choice (1 for Producer, 2 for Consumer, 3 to Exit)
- Case 1 (Producer):
3
- Check if the mutex is unlocked (mutex == 1) and the buffer is not full (empty != 0)
- Case 2 (Consumer):
- Check if the mutex is unlocked (mutex == 1) and the buffer is not empty (full != 0)
- Case 3 (Exit):
- Default:
4
Simple Simulation Of The Grep() Command
1. Initialize:
- Declare variables:
- 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
Simple Demonstration Of The Execvp() System Call
1. Initialize:
- Read the command using fgets() and store it in the command array.
- Set the last element of the args array to NULL to indicate the end of the argument
list.
5. Child process:
- Execute the new program using execvp(), passing the command name and
arguments.
6. Parent process:
- 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.
2. Initialize:
3. FIFO algorithm:
- 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.
4. Search function:
5. Print statistics:
7
C-SCAN (Circular SCAN) Algorithm
1. Initialize:
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.
- If the head is at the last request, move to the maximum cylinder value (CYMAX).
- Calculate the absolute distance between the current head position and the next
request.
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.
- Verify that the max resources and allocated resources do not exceed the total
resources for each resource type.
- Subtract allocated resources from total resources for each resource type.
- Subtract allocated resources from max resources for each process and resource
type.
- While there are still processes that need resources (ch > 0):
- Mark the process as allocated (f[I] = 1) and add it to the safe sequence (state).
- 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:
2. Fork:
3. Child Process:
- If this is the child process (pid == 0), execute the ls command with the -l argument
using execlp().
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:
10
First-come-first-served (FCFS) Scheduling Algorithm.
1. Input:
2. Initialize:
- Set the waiting time (wt) and turn-around time (tt) for each process to 0.
- 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).
- Print the process number, burst time, waiting time, and turn-around time for each
process.
- 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).
11
Round Robin Scheduling Algorithm.
1. Initialize:
- 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.
- 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).
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).
- For each process, read its size from the user and store it in the p array.
- For each memory block, read its size from the user and store it in the m array.
- 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.
- For each process, print whether it was allocated to a memory block or not.
13
Priority Scheduling Algorithm.
1. Initialize:
- 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:
- For each process, read its burst time and priority from the user and store them in the
pr array.
- Use a simple sorting algorithm (insertion sort) to sort the processes in ascending
order of priority.
- 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).
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.
3. LRU algorithm:
- 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.
4. Print statistics:
15
Optimal Page Replacement
1. Initialize:
- Define the number of pages (n), the number of frames (f), and the page reference
sequence (pages).
- 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).
4. Print statistics:
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).
- 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.
4. Print statistics:
17
Dining Philosophers Problem
1. Initialize:
2. Philosopher Thread:
- The thread function takes an integer argument (id) representing the philosopher's ID.
3. Thinking:
- 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.
- 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:
- They print a message indicating they've put down the right 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:
19
Stat sytem call
20
Dir system call
21
Fork system call
22