Operating Systems Lab Programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

1.a) Write a program to implement Process System Calls.

b) Write a program to implement I/O System Calls.


Process system call
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
pid_t pid = fork();

if(pid == 0) {
printf("Child => PID: %d PID: %d\n", getppid(), getpid());
exit(EXIT_SUCCESS);
}
else if(pid > 0) {
printf("Parent => PID: %d\n", getppid());
printf("Waiting for child process to finish.\n");
wait(NULL);
printf("Child process finished.\n");
}
else {
printf("Unable to create child process.\n");
}

return EXIT_SUCCESS;
}

2. fork()
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

void childTask() {
printf("Hello World\n");
}

void parentTask() {
printf("Main task.\n");
}

int main(void) {
pid_t pid = fork();

if(pid == 0) {
childTask();
exit(EXIT_SUCCESS);
}
else if(pid > 0) {
wait(NULL);
parentTask();
}
else {
printf("Unable to create child process.");
}

return EXIT_SUCCESS;
}

b) Implementing I/O System Calls:


3. I/O system calls
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

int main() {
int fd;
ssize_t bytesRead, bytesWritten;
char buffer[100];

// Open the file "example.txt" with read-only permissions


fd = open("JYO.txt", O_RDONLY);
if (fd < 0) {
perror("Error opening file");
return 1;
}

// Read from the file


bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead < 0) {
perror("Error reading file");
close(fd);
return 1;
}

// Null-terminate the buffer to make it a valid C-string


buffer[bytesRead] = '\0';

// Write the contents to standard output


bytesWritten = write(STDOUT_FILENO, buffer, bytesRead);
if (bytesWritten < 0) {
perror("Error writing to stdout");
close(fd);
return 1;
}

// Close the file


if (close(fd) < 0) {
perror("Error closing file");
return 1;
}

// Print the number of characters read and written


printf("\nNumber of characters read: %ld\n", bytesRead);
printf("Number of characters written: %ld\n", bytesWritten);

return 0;
}

OUTPUT:
HELLO WORLD:
Number of characters read: 12
Number of characters written: 12
2.Write a program to implement named and unnamed pipes.
1.Unnamed Pipe (Parent-Child Communication):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[100];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
close(pipefd[1]); // Close the write end of the pipe
int bytesRead = read(pipefd[0], buffer, sizeof(buffer));
close(pipefd[0]); // Close the read end of the pipe
printf("Child: Received message from parent: %.*s\n", bytesRead, buffer);
} else {
// Parent process
close(pipefd[0]); // Close the read end of the pipe
char message[] = "Hello from parent!";
write(pipefd[1], message, sizeof(message));
close(pipefd[1]); // Close the write end of the pipe
}
return 0;
}

3. Demonstrate File Permissions.


DESCRIPTION:
Here In This Program "Test_File.Txt" File Created In The Same Directory, And Its Permissions Will Be
Set As Specified In The Program.
Constants S_IRUSR, S_IWUSR, S_IRGRP, and S_IROTH:

⮚ S_IRUSR: This constant represents the permission bit for the owner (user) of the file to read the
file. It stands for "read permission for user."
⮚ S_IWUSR: This constant represents the permission bit for the owner (user) of the file to write to
the file. It stands for "write permission for user."
⮚ S_IRGRP: This constant represents the permission bit for the group associated with the file to read
the file. It stands for "read permission for group."
⮚ S_IROTH: This constant represents the permission bit for others (users who are not the owner and
not in the group) to read the file. It stands for "read permission for others."

S_IRUSR: Read permission for the user.


S_IWUSR: Write permission for the user.
S_IRGRP: Read permission for the group.
S_IROTH: Read permission for others.
PROGRAM
#include <stdio.h>
#include <sys/stat.h>
int main() {
const char *filename = "test_file.txt";
int result;
// Creating a test file
FILE *file = fopen(filename, "w");
if (file == NULL) {
perror("Error creating file");
return 1;
}
fclose(file);
// Changing permissions
result = chmod(filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (result != 0) {
perror("Error changing permissions");
return 1;
}
printf("Permissions changed successfully.\n");
return 0;
}
Output:
Permissions changed successfully.
4. Analyze the following CPU Scheduling Algorithms:
a) FCFS b) SJF (Preemptive) c) Priority d) Round Robin

4a.)
AIM: To write a c program to simulate the CPU scheduling algorithm First Come First Serve (FCFS)
DESCRIPTION:
To calculate the average waiting time using the FCFS algorithm first the waiting time of the first process
is kept zero and the waiting time of the second process is the burst time of the first process and the
waiting time of the third process is the sum of the burst times of the first and the second process and so on.
After calculating all the waiting times the average waiting time is calculated as the average of all the
waiting times. FCFS mainly says first come first serve the algorithm which came first will be served first.
PROGRAM:

#include<stdio.h>

int main()
{
int at[20], bt[20], wt[20], tat[20], ct[20], rt[20], i, n;
float wtavg, tatavg, throughput;
int total_bt = 0;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("\nEnter Arrival Time for Process %d -- ", i);
scanf("%d", &at[i]);
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
total_bt += bt[i];
}
wt[0] = 0;
tat[0] = bt[0];
ct[0] = at[0] + bt[0];
rt[0] = wt[0];
wtavg = 0;
tatavg = tat[0];
for(i = 1; i < n; i++)
{
if (ct[i-1] > at[i]) {
wt[i] = ct[i-1] - at[i];
} else {
wt[i] = 0;
}
rt[i] = wt[i];
tat[i] = wt[i] + bt[i];
ct[i] = at[i] + tat[i];

wtavg += wt[i];
tatavg += tat[i];
}
throughput = (float)n / (ct[n-1] - at[0]);
printf("\tPROCESS\tARRIVAL TIME\tBURST TIME\tWAITING TIME\tTURNAROUND TIME\
tCOMPLETION TIME\tRESPONSE TIME\n");

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


printf("\n\tP%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d", i, at[i], bt[i], wt[i], tat[i], ct[i], rt[i]);
printf("\nAverage Waiting Time -- %f", wtavg / n);
printf("\nAverage Turnaround Time -- %f", tatavg / n);
printf("\nThroughput -- %f", throughput);

return 0;
}
OUTPUT:
Enter the number of processes -- 4

Enter Arrival Time for Process 0 -- 0


Enter Burst Time for Process 0 -- 8

Enter Arrival Time for Process 1 -- 1


Enter Burst Time for Process 1 -- 4

Enter Arrival Time for Process 2 -- 2


Enter Burst Time for Process 2 -- 2
Enter Arrival Time for Process 3 -- 3
Enter Burst Time for Process 3 -- 1
PROCESS ARRIVAL TIME BURST TIME WAITING TIME
TURNAROUND TIME COMPLETION TIME RESPONSE TIME

P0 0 8 0 8 8 0
P1 1 4 7 11 12 7
P2 2 2 10 12 14 10
P3 3 1 11 12 15 11
Average Waiting Time -- 7.000000
Average Turnaround Time -- 10.750000
Throughput -- 0.266667

b) Shortest job first (preemptive)

#include<stdio.h>
#include<string.h>
int main()
{
// Variable and array declarations
int bt[20], at[10], n, i, j, temp, st[10], ft[10], wt[10], tat[10];
int totwt = 0, tottat = 0;
float awt, atat;
char p[10][10], t[10];

// User input for the number of processes


printf("Enter the number of processes:");
scanf("%d", &n);

// Input process details (name, arrival time, execution time)


for (i = 0; i < n; i++)
{
printf("Enter process name, arrival time & execution time:");
scanf("%s%d%d", p[i], &at[i], &bt[i]);
}

// Sort processes based on burst time using simple sorting algorithm


for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
if (bt[i] < bt[j])
{
// Swap arrival times, burst times, and process names
temp = at[i];
at[i] = at[j];
at[j] = temp;
temp = bt[i];
bt[i] = bt[j];
bt[j] = temp;
strcpy(t, p[i]);
strcpy(p[i], p[j]);
strcpy(p[j], t);
}
}

// Calculate scheduling metrics for each process


for (i = 0; i < n; i++)
{
if (i == 0)
st[i] = at[i];
else
st[i] = ft[i - 1];
wt[i] = st[i] - at[i];
ft[i] = st[i] + bt[i];
tat[i] = ft[i] - at[i];
totwt += wt[i];
tottat += tat[i];
}

// Calculate average waiting time and average turnaround time


awt = (float)totwt / n;
atat = (float)tottat / n;

// Print process details and metrics


printf("\nName\tArrival Time\tExecution Time\tWaiting Time\tTurnaround Time");
for (i = 0; i < n; i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d", p[i], at[i], bt[i], wt[i], tat[i]);
printf("\nAverage waiting time: %f", awt);
printf("\nAverage turnaround time: %f", atat);

return 0;
}

INPUT:
Enter the number of process:3
Enter process name, arrival time& execution time:p1
2
5
Enter process name, arrival time& execution time:p2
5
2
Enter process name, arrival time& execution time:p3
0
9
OUTPUT:

Pame atrrivaltime executiontime waitingtime tattime


p2 5 2 0 2
p1 2 5 5 10
p3 0 9 12 21
Average waiting time is:5.666667Average turnaroundtime is:11.000000

c) PRIORITY:
AIM: To write a c program to simulate the CPU scheduling priority algorithm.
DESCRIPTION:
To calculate the average waiting time in the priority algorithm, sort the burst times according to their
priorities and then calculate the average waiting time of the processes. The waiting time of each process is
obtained by summing up the burst times of all the previous processes.
PROGRAM:
#include<stdio.h>
Int main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp; float wtavg,
tatavg;
clrscr();
printf("Enter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++){
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i); scanf("%d
%d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k]){
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND
TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n); printf("\nAverage
Turnaround Time is --- %f",tatavg/n);
}

INPUT
Enter the number of processes -- 5
Enter the Burst Time & Priority of Process 0 --- 10 3
Enter the Burst Time & Priority of Process 1 --- 1 1
Enter the Burst Time & Priority of Process 2 --- 2 4
Enter the Burst Time & Priority of Process 3 --- 1 5
Enter the Burst Time & Priority of Process 4 --- 5 2
OUTPUT
PROCESS PRIORITY BURST TIME WAITING TIME TURNAROUND TIME
11101
42516
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is --- 8.200000
Average Turnaround Time is --- 12.000000

D). ROUND ROBIN:


AIM: To simulate the CPU scheduling algorithm round-robin.
DESCRIPTION:
To aim is to calculate the average waiting time. There will be a time slice, each process should e
executed within that time-slice and if not it will go to the waiting state so first check whether the burst
time is less than the time-slice. If it is less than it assign the waiting time to the sum of the total times. If it
is greater than the burst-time then subtract the time slot from the actual burst time and increment it by
time-slot and the loop continues until all the processes are completed.

#include<stdio.h>
int main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;

printf("Enter the no of processes -- ");


scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t) {
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else {
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++){
wa[i]=tat[i]-
ct[i]; att+=tat[i];
awt+=wa[i];}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}

INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 – 3
Enter the size of time slice – 3
OUTPUT:
PROCESS BURST TIME WAITING TIME TURNAROUNDTIME
1 24 6 30
2347
3 3 7 10
The Average Turnaround time is – 15.666667 The
Average Waiting time is ------------ 5.666667

5.Design solutions for the following synchronization problems:


a) Producer Consumer Problem b) Dining Philosophers Problem.
a) Producer Consumer Problem
AIM: To Write a C program to simulate producer-consumer problem using semaphores.
DESCRIPTION
Producer consumer problem is a synchronization problem. There is a fixed size buffer where theproducer
produces items and that is consumed by a consumer process. One solution to the producerconsumer
problem uses shared memory. To allow producer and consumer processes to run concurrently, there must
be available a buffer of items that can be filled by the producer and emptied by the consumer. This buffer
will reside in a region of memory that is shared by the producer and consumer processes. The producer
and consumer must be synchronized, so that the consumer does not try to consume an item that has not yet
been produced.
PROGRAM
#include <stdio.h>

int main() {
int buffer[10], bufsize, in, out, produce, consume, choice = 0;
in = 0;
out = 0;
bufsize = 10;

while (choice != 3) {
printf("\n1. Produce \t 2. Consume \t 3. Exit");
printf("\n Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
if ((in + 1) % bufsize == out) {
printf("\nBuffer is Full");
} else {
printf("\nEnter the value: ");
scanf("%d", &produce);
buffer[in] = produce;
in = (in + 1) % bufsize;
}
break;

case 2:
if (in == out) {
printf("\nBuffer is Empty");
} else {
consume = buffer[out];
printf("\nThe consumed value is %d", consume);
out = (out + 1) % bufsize;
}
break;

case 3:
printf("\nExiting the program.\n");
break;

default:
printf("\nInvalid choice. Please enter 1, 2, or 3.\n");
}
}

return 0;
}
OUTPUT
1. Produce 2. Consume 3. Exit
Enter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit
Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit
Enter your choice: 3
b) Dining-Philosophers problem.
AIM: To Write a C program to simulate the concept of Dining-Philosophers problem.
DESCRIPTION
The dining-philosophers problem is considered a classic synchronization problem because it is an example
of a large class of concurrency-control problems. It is a simple representation of the need to allocate
several resources among several processes in a deadlock-free and starvation-free manner. Consider five
philosophers who spend their lives thinking and eating. The philosophers share a circular table surrounded
by five chairs,each belonging to one philosopher. In the center of the table is a bowl of rice, and the table
is laid with five single chopsticks. When a philosopher thinks, she does not interact with her colleagues.
From time to time, a philosopher gets hungry and tries to pick up the two chopsticks that are closest to her
(the chopsticks that are between her and her left and right neighbors). A philosopher may pick up only one
chopstick at a time.
Obviously, she cam1ot pick up a chopstick that is already in the hand of a neighbor. When a hungry
philosopher has both her chopsticks at the same time, she eats without releasing her chopsticks. When she
is finished eating, she puts down both of her chopsticks and starts thinking again. The dining-philosophers
Problem may lead to a deadlock situation and hence some rules have to be framed to avoid the occurrence
of deadlock.

PROGRAM
#include <stdio.h>
#include <stdlib.h> // Added for abs() function

int tph, philname[20], status[20], howhung, hu[20], cho;

void one();
void two();

int main() {
int i;
printf("\nDINING PHILOSOPHER PROBLEM");
printf("\nEnter the total number of philosophers: ");
scanf("%d", &tph);

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


philname[i] = (i + 1);
status[i] = 1;
}

printf("How many are hungry: ");


scanf("%d", &howhung);
if (howhung == tph) {
printf("\nAll are hungry...");
printf("\nDeadlock stage will occur.");
printf("\nExiting\n");
} else {
for (i = 0; i < howhung; i++) {
printf("Enter philosopher %d position: ", (i + 1));
scanf("%d", &hu[i]);
status[hu[i]] = 2;
}

do {
printf("\n1. One can eat at a time\n2. Two can eat at a time\n3. Exit\nEnter your choice: ");
scanf("%d", &cho);

switch (cho) {
case 1:
one();
break;
case 2:
two();
break;
case 3:
exit(0);
default:
printf("\nInvalid option.\n");
}
} while (1);
}

return 0;
}

void one() {
int pos = 0, x, i;
printf("\nAllow one philosopher to eat at any time\n");

for (i = 0; i < howhung; i++, pos++) {


printf("\nP %d is granted to eat", philname[hu[pos]]);
for (x = pos + 1; x < howhung; x++) {
printf("\nP %d is waiting", philname[hu[x]]);
}
}
}

void two() {
int i, j, s = 0, t, r, x;
printf("\nAllow two philosophers to eat at the same time\n");

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


for (j = i + 1; j < howhung; j++) {
if (abs(hu[i] - hu[j]) >= 1 && abs(hu[i] - hu[j]) != 4) {
printf("\n\nCombination %d", (s + 1));
t = hu[i];
r = hu[j];
s++;
printf("\nP %d and P %d are granted to eat", philname[hu[i]], philname[hu[j]]);
for (x = 0; x < howhung; x++) {
if ((hu[x] != t) && (hu[x] != r)) {
printf("\nP %d is waiting", philname[hu[x]]);
}
}
}
}
}
}
INPUT
DINING PHILOSOPHER PROBLEM
Enter the total no. of philosophers: 5
How many are hungry : 3
Enter philosopher 1 position: 2
Enter philosopher 2 position: 4
Enter philosopher 3 position: 5
OUTPUT
1. One can eat at a time 2.Two can
eat at a time 3.Exit Enter your choice: 1
Allow one philosopher to eat at any time
P 3 is granted to eat
P 3 is waiting
P 5 is waiting
P 0 is waiting
P 5 is granted to eat
P 5 is waiting
P 0 is waiting
P 0 is granted to eat
P 0 is waiting

1.One can eat at a time 2.Two can eat at a time 3.Exit


Enter your choice: 2
Allow two philosophers to eat at same time
combination 1
P 3 and P 5 are granted to eat
P 0 is waiting
combination 2
P 3 and P 0 are granted to eat
P 5 is waiting
combination 3
P 5 and P 0 are granted to eat
P 3 is waiting
1.One can eat at a time 2.Two can
eat at a time 3.Exit Enter your choice: 3
6.Design Banker’s Algorithm for Deadlock Avoidance. Find the safe sequence. If Maximum request
of any one process is changed, detect whether a deadlock has occurred or not. Consider the number
of resources are three and Jobs are five.
AIM: To Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)
DESCRIPTION:
Deadlock is a situation where in two or more competing actions are waiting f or the other to finish, and
thus neither ever does. When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of resources in the
system. When the user request a set of resources, the system must determine whether the allocation of
each resources will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.
Data structures
n-Number of process, m-number of resource types.
Available: Available[j]=k, k – instance of resource type Rj is available. Max:
If max[i, j]=k, Pi may request at most k instances resource Rj.
Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj Need:
If Need[I, j]=k, Pi may need k more instances of resource type Rj,
Need[I, j]=Max[I, j] - Allocation[I, j];
Safety Algorithm
1. Work and Finish be the vector of length m and n respectively, Work=Available and
Finish[i] =False.
2. Find an i such that both
Finish[i] =False
Need<=Work If no such I
exists go to step 4.
3. work= work + Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.

Resource request algorithm


Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi
wants k instances of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are
available.
3. Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows;
Available=Available-Request I;
Allocation I=Allocation +Request I;
Need i=Need i- Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Request i and the
old resource-allocation state is restored.

SOURCE CODE :
#include<stdio.h>
#include<string.h>
int main() {
int alloc[10][10], max[10][10];
int avail[10], work[10], total[10];
int i, j, k, n, need[10][10];
int m;
int count = 0, c = 0;
char finish[10];

printf("Enter the number of processes and resources: ");


scanf("%d %d", &n, &m);

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


finish[i] = 'n';

printf("Enter the maximum claim matrix:\n");


for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
scanf("%d", &max[i][j]);

printf("Enter the allocation matrix:\n");


for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
scanf("%d", &alloc[i][j]);

printf("Enter the available resource vector:\n");


for (i = 0; i < m; i++)
scanf("%d", &total[i]);

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


avail[i] = 0;

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


for (j = 0; j < m; j++)
avail[j] += alloc[i][j];

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


work[i] = avail[i];

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


work[j] = total[j] - work[j];

A:
for (i = 0; i < n; i++) {
c = 0;
for (j = 0; j < m; j++)
if ((need[i][j] <= work[j]) && (finish[i] == 'n'))
c++;
if (c == m) {
printf("All resources can be allocated to Process %d\n", i + 1);
printf("Available resources are:");
for (k = 0; k < m; k++) {
work[k] += alloc[i][k];
printf("%4d", work[k]);
}
printf("\n");
finish[i] = 'y';
printf("Process %d executed?: %c\n", i + 1, finish[i]);
count++;
}
}

if (count != n)
goto A;
else
printf("\nSystem is in a safe state.\n");

return 0;
}
OUTPUT
Enter the no. of processes and resources: 4 3
Enter the claim matrix:
322
613
314
422
Enter the allocation matrix:
100
612
211
002
Resource vector:9 3 6
All the resources can be allocated to Process 2 Available resources are: 6 2 3
Process 2 executed?:y
All the resources can be allocated to Process 3 Available resources are: 8 3 4
Process 3 executed?:y
All the resources can be allocated to Process 4 Available resources are: 8 3 6
Process 4 executed?:y
All the resources can be allocated to Process 1 Available resources are: 9 3 6
Process 1 executed?:y
System is in safe mode
The given state is safe state

7. Implement the following Algorithms:


a) Worst-fit b) Best-fit c) First-fit
AIM: To Write a C program to simulate the following contiguous memory allocation techniques
DESCRIPTION
One of the simplest methods for memory allocation is to divide memory into several fixed-sized
partitions. Each partition may contain exactly one process. In this multiple-partition method, when a
partition is free, a process is selected from the input queue and is loaded into the free partition. When the
process terminates, the partition becomes available for another process. The operating system keeps a
table indicating which parts of memory are available and which are occupied. Finally, when a process
arrives and needs memory, a memory section large enough for this process is provided. When it is time
toload or swap a process into main memory, and if there is more than one free block of memory of
sufficient size, then the operating system must decide which free block to allocate. Best-fit strategy
chooses the block that is closest in size to the request. First-fit chooses the first available block that is
large enough. Worst-fit chooses the largest available block.
PROGRAM
a)WORST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
int main()
{
Int frag[max],b[max],f[max],i,j,nb,nf,temp; static int bf[max],ff[max];
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment
11154
24373
b)BEST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
int main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
printf("Block %d:",i);
scanf("%d",&b[i]);
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j;
lowest=temp;
}
}}
frag[i]=lowest; bf[ff[i]]=1; lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock
Size\tFragment"); for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size
Block No
Block Size
Fragment
11221
24151

c)FIRST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
Int main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highes
t=0; static int bf[max],ff[max];
printf("\n\tMemory Management Scheme - Worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
}
}
frag[i]=highest; bf[ff[i]]=1; highest=0;
}
ff[i]=j; highest=temp;
}
printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment
11376
24151

8.Implement the following Page Replacement Algorithms


a) FIFO b) LFU c) LRU d) Optimal
AIM: To implement FIFO page replacement technique.
a) FIFO b) LRU c) OPTIMAL
DESCRIPTION:
Page replacement algorithms are an important part of virtual memory management and it helps the OS to
decide which memory page can be moved out making space for the currently needed page. However, the
ultimate objective of all page replacement algorithms is to reduce the number of page faults.
FIFO-This is the simplest page replacement algorithm. In this algorithm, the operating system keeps track
of all pages in the memory in a queue, the oldest page is in the front of the queue. When a page needs to
be replaced page in the front of the queue is selected for removal.
LRU-In this algorithm page will be replaced which is least recently used
OPTIMAL- In this algorithm, pages are replaced which would not be used for the longest duration of
time in the future. This algorithm will give us less page fault when compared to other page replacement
algorithms.
A) FIRST IN FIRST OUT
SOURCE CODE :
#include<stdio.h>
#include<conio.h> int fr[3];
int main()
{
void display();
int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};
int
flag1=0,flag2=0,pf=0,frsize=3,top=0;
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0; flag2=0; for(i=0;i<12;i++)
{
if(fr[i]==page[j])
{
flag1=1; flag2=1; break;
}
}
if(flag1==0)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j]; flag2=1; break;
}
}
}
if(flag2==0)
{
fr[top]=page[j];
top++;
pf++;
if(top>=frsize)
top=0;
}
display();
}
printf("Number of page faults : %d ",pf+frsize);
}
void display()
{
int i; printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}
OUTPUT:
2 -1 -1
2 3 -1
2 3 -1
231
531
521
524
524
324
324
354
352
Number of page faults: 9

B) LEAST RECENTLY USED


AIM: To implement LRU page replacement technique.
SOURCE CODE :
#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0,flag2=0;
for(i=0;i<3;i++)
{
if(fr[i]==p[j])
{
flag1=1;
flag2=1; break;
}
}
if(flag1==0)
{
for(i=0;i<3;i++)
{
if(fr[i]==-1)
{
fr[i]=p[j]; flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<3;i++)
fs[i]=0;
for(k=j-1,l=1;l<=frsize-1;l++,k--)
{
for(i=0;i<3;i++)
{
if(fr[i]==p[k]) fs[i]=1;
}}
for(i=0;i<3;i++)
{
if(fs[i]==0)
index=i;
}
fr[index]=p[j];
pf++;
}
display();
}
printf("\n no of page faults :%d",pf+frsize);
getch();
}
void display()
{
int i; printf("\n");
for(i=0;i<3;i++)
printf("\t%d",fr[i]);
}
OUTPUT:
2 -1 -1
2 3 -1
2 3 -1
231
251
251
254
254
354
352
352
352
No of page faults: 7
C) OPTIMAL
AIM: To implement optimal page replacement technique.
SOURCE CODE:
/* Program to simulate optimal page replacement */
#include<stdio.h>
#include<conio.h>
int fr[3], n, m;
void
display();
void main()
{
int i,j,page[20],fs[10];
int
max,found=0,lg[3],index,k,l,flag1=0,flag2=0,pf=0;
float pr;
clrscr();
printf("Enter length of the reference string: ");
scanf("%d",&n);
printf("Enter the reference string: ");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter no of frames: ");
scanf("%d",&m);
for(i=0;i<m;i++)
fr[i]=-1; pf=m;
Page 36
for(j=0;j<n;j++)
{
flag1=0; flag2=0;
for(i=0;i<m;i++)
{
if(fr[i]==page[j])
{
flag1=1; flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j]; flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-j;
break;
}
}
}
found=0;
for(i=0;i<m;i++)
{
if(lg[i]==0)
{
index=i;
found = 1;
Page 37
break;
}
}
if(found==0)
{
max=lg[0]; index=0;
for(i=0;i<m;i++)
{
if(max<lg[i])
{
max=lg[i];
index=i;
}
}
}
fr[index]=page[j];
pf++;
}
display();
}
printf("Number of page faults : %d\n", pf);
pr=(float)pf/n*100;
printf("Page fault rate = %f \n", pr); getch();
}
void display()
{
int i; for(i=0;i<m;i++)
printf("%d\t",fr[i]);
printf("\n");
}
OUTPUT:
Enter length of the reference string: 12
Enter the reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Enter no of frames: 3
1 -1 -1
1 2 -1
123
124
124
124
125
125
125
325
425
425
Number of page faults : 7 Page fault rate = 58.333332

9.Implement the following Disk Scheduling Algorithms


a) FCFS b) SSTF c) SCAN d) CSCAN

AIM: To Write a C program to simulate disk scheduling algorithms


a) FCFS b) SCAN c) C-SCAN
DESCRIPTION
One of the responsibilities of the operating system is to use the hardware efficiently. For the disk drives,
meeting this responsibility entails having fast access time and large disk bandwidth. Both the access time
and the bandwidth can be improved by managing the order in which disk I/O requests are serviced which
is called as disk scheduling. The simplest form of disk scheduling is, of course, the first-come, first-served
(FCFS) algorithm. This algorithm is intrinsically fair, but it generally does not provide the fastest service.
In the SCAN algorithm, the disk arm starts at one end, and moves towards the other end, servicing
requests as it reaches each cylinder, until it gets to the other end of the disk. At the other end, the direction
of head movement is reversed, and servicing continues. The head continuously scans back and forth across
the disk. C-SCAN is a variant of SCAN designed to provide a more uniform wait time. Like SCAN, C-
SCAN moves the head from one end of the disk to the other, servicing requests along the way. When the
head reaches the other end, however, it immediately returns to the beginning of the disk without servicing
any requests on the return trip.

PROGRAM
A) FCFS DISK SCHEDULING ALGORITHM
#include<stdio.h>
int main()
{
int t[20], n, I, j, tohm[20], tot=0; float avhm;
printf(“enter the no.of tracks”);
scanf(“%d”,&n);
printf(“enter the tracks to be traversed”);
for(i=2;i<n+2;i++)
scanf(“%d”,&t*i+);
for(i=1;i<n+1;i++)
{
tohm[i]=t[i+1]-t[i];
if(tohm[i]<0)
tohm[i]=tohm[i]*(-1);
}
for(i=1;i<n+1;i++)
tot+=tohm[i];
avhm=(float)tot/n;
printf(“Tracks traversed\tDifference between tracks\n”);
for(i=1;i<n+1;i++)
printf(“%d\t\t\t%d\n”,t*i+,tohm*i+);
printf("\nAverage header movements:%f",avhm);
getch();
}
INPUT
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160 184
OUTPUT
Tracks traversed Difference between tracks
55 58 60 70 18 90 45 3 2 10 52 72 150 160 184 60 10 24
Average header movements:30.888889

B) SCAN DISK SCHEDULING ALGORITHM


#include<stdio.h>
int main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
printf("enter the no of tracks to be traveresed");
scanf("%d'",&n);
printf("enter the position of head");
scanf("%d",&h);
t[0]=0;t[1]=h;
printf("enter the tracks");
for(i=2;i<n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<n+2;i++)
{
for(j=0;j<(n+2)-i-1;j++)
{
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}}}
for(i=0;i<n+2;i++)
if(t[i]==h)
j=i;k=i;
p=0;
while(t[j]!=0)
{
atr[p]=t[j]; j--;
p++;
}
atr[p]=t[j];
for(p=k+1;p<n+2;p++,k++)
atr[p]=t[k+1];
for(j=0;j<n+1;j++)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else
d[j]=atr[j+1]-atr[j];
sum+=d[j];
}
printf("\nAverage header movements:%f",(float)sum/n);

}
INPUT
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160 184
OUTPUT
Tracks traversed Difference between tracks
150 160 184 90 70 60 58 55 18 50 10 24 94 20 10 2 3 37
Average header movements: 27.77

C) C-SCAN DISK SCHEDULING ALGORITHM


#include<stdio.h>
int main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
printf("enter the no of tracks to be traveresed");
scanf("%d'",&n);
printf("enter the position of head");
scanf("%d",&h);
t[0]=0;t[1]=h;
printf("enter total tracks");
scanf("%d",&tot);
t[2]=tot-1;
printf("enter the tracks");
for(i=3;i<=n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<=n+2;i++)
for(j=0;j<=(n+2)-i-1;j++)
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp
}
for(i=0;i<=n+2;i++)
if(t[i]==h);
j=i;break;
p=0;
while(t[j]!=tot-1)
{
atr[p]=t[j];
j++;
p++;
}
atr[p]=t[j];
p++;
i=0;
while(p!=(n+3) && t[i]!=t[h])
{
atr[p]=t[i]; i++;
p++;
}
for(j=0;j<n+2;j++)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else
d[j]=atr[j+1]-atr[j];
sum+=d[j];
}
printf("total header movements%d",sum);
printf("avg is %f",(float)sum/n);
}

INPUT
Enter the track position : 55 58 60 70 18 90 150 160 184
Enter starting position : 100
OUTPUT
Tracks traversed Difference Between tracks
150 160 184 18 55 58 60 70 90 50 10 24 240 37 3 2 10 20
Average seek time : 35.7777779

10.Implement the following file allocation strategies:


a) Contiguous Allocation b) Linked Allocation
a)contiguous Allocation:

AIM: To write a C program for implementing Contiguous file allocation method


DESCRIPTION:
The most common form of file structure is the sequential file in this type of file, a fixed format is used for
records. All records (of the system) have the same length, consisting of the same number of fixed length
fields in a particular order because the length and position of each field are known, only the values of
fields need to be stored, the field name and length for each field are attributes of the file structure.
SOURCE CODE :
#include<stdio.h>
int main()
{
int f[50],i,st,j,len,c,k;
for(i=0;i<50;i++)
f[i]=0;
X:
printf("\n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Block already allocated");
break;
}
if(j==(st+len))
printf("\n the file is allocated to disk");
printf("\n if u want to enter more files?(y-1/n-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit();

}
OUTPUT:
Enter the starting block & length of file 4 10
4->1
5->1
6->1
7->1
8->1
9->1
10->1
11->1
12->1
13->1
The file is allocated to disk.

b) AIM: To implement linked file allocation technique.


DESCRIPTION:
In the chained method file allocation table contains a field which points to starting
block of memory. From it for each bloc a pointer is kept to next successive block. Hence,
there is no external fragmentation
SOURCE CODE :
#include<stdio.h>
int main()
{
int f[50],p,i,j,k,a,st,len,n,c;
for(i=0;i<50;i++)
f[i]=0;
printf("Enter how many blocks that are already allocated");
scanf("%d",&p);
printf("\nEnter the blocks no.s that are already allocated");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
X:
printf("Enter the starting index block &
length"); scanf("%d%d",&st,&len); k=len;
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d->file is already allocated",j);
k++;
}
}
printf("\n If u want to enter one more file? (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto
X;
else
exit();
}
OUTPUT:
Enter how many blocks that are already allocated 3 Enter the blocks no.s that are already allocated 4 7
Enter the starting index block & length 3 7 9
3->1
4->1 file is already allocated
5->1
6->1
7->1 file is already allocated
8->1
9->1file is already allocated
10->1
11->1
12->1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy