0% found this document useful (0 votes)
6 views30 pages

Operating System File

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)
6 views30 pages

Operating System File

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/ 30

EXPERIMENT-1

1.OBJECTIVE:-
The objective of this experiment is to demonstrate basic file handling operations in C, such as
opening, reading, writing, and closing files. The experiment will cover:
1.Creating and writing data to a file.
2.Reading data from a file.
3.Appending data to an existing file.
4.Understanding the use of file pointers and the different file modes in C.
2.SYSTEM REQUIREMENTS:-
Hardware Requirements:
1.Any standard computer with a processor capable of running C programs.
2.Minimum 1GB RAM for basic file operations.
Software Requirements:
1.Operating System: Windows/Linux/macOS (any system with C compiler support).
2.Compiler: GCC, Clang, or any C compiler (support for file I/O operations).
3.Development Environment: Any IDE or text editor (VSCode, Code::Blocks, etc.).
3.FILE HANDLING:-
In C programming, file handling allows a program to read from and write to files, providing
persistent storage for data. Files are opened using the fopen() function and can be handled using
different modes such as:
1."r": Open for reading (file must exist).
2."w": Open for writing (creates a new file or overwrites an existing file).
3."a": Open for appending (writes data at the end of the file).
4."rb", "wb", "ab": Binary modes for reading, writing, and appending binary data.
The key operations involved in file handling include:
1.Opening a file with fopen().
2.Reading from a file using functions like fgetc(), fgets(), or fread().
3.Writing to a file with fputc(), fputs(), or fwrite().
4.Closing the file with fclose() to free resources.
4.PROGRAM FOR FILE HANDLING:-
// C program to Open a File,
// Write in it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
// Declare the file pointer
FILE* filePointer;
// Get the data to be written in file
char dataToBeWritten[50] = "GeeksforGeeks-A Computer "
"Science Portal for Geeks";
// Open the existing file GfgTest.c using fopen()
// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {
printf("The file is now opened.\n");
// Write the dataToBeWritten into the file
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fputs()
fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}
// Closing the file using fclose()
fclose(filePointer);
printf("Data successfully written in file "
"GfgTest.c\n");
printf("The file is now closed.");
}
return 0;
}
5.OUTPUT:-

6.RESULT:-
When the program is executed, it performs the following operations:
1.It creates or overwrites the file example.txt with the line "This is a sample text written to the file."
2.It reads the contents of the file and prints it to the console:
EXPERIMENT –2
1.OBJECTIVE:-
To simulate the Dining Philosophers Problem using threads mutexes, demonstrating how to manage
concurrent access to shared resources and prevent issues like deadlock and starvation.

2.SYSTEM REQUIREMENTS:-

Hardware Requirements:

1.A computer with a processor capable of handling multi-threading.


2.Minimum 2GB of RAM (depends on the system load and number of philosophers).
Software Requirements:

1.Operating System: Windows/Linux/macOS (with POSIX threads or pthread library support).


2.Compiler: GCC, Clang, or any C language compiler with support for multi-threading.
3.Development Environment: Any IDE or text editor (VSCode , Code:Blocks , Sublime Text, etc.).
4.POSIX threads (pthread library) for managing threads in C.

3.DINING PHILOSOPHER PROBLEM:-

The Dining Philosophers Problem is a classic synchronization problem where multiple philosophers
sit around a table, thinking and eating. To eat, each philosopher needs two forks—one on the left
and one on the right. The challenge is to ensure that no philosopher experiences deadlock (waiting
forever for forks), starvation (being indefinitely blocked from eating), or race conditions
(conflicting access to forks)..
The main issues involved are:
• Deadlock: Philosophers may get stuck waiting for each other to release forks.
• Starvation: Some philosophers may never get a chance to eat.
• Synchronization: Proper management of resources (forks) is needed to avoid these problems.
In this experiment, we simulate the problem using threads and mutexes to synchronize access to
shared resources (forks), preventing deadlock and ensuring fair resource allocation.

In this experiment, the key goals are:


1. To implement a solution to the Dining Philosophers problem using threads.
2. To use mutexes to avoid race conditions and deadlock.
3. To explore ways to prevent starvation and ensure fair resource allocation.

4.PROGRAM FOR DINING PHILOSOPHER PROBLEM:-

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_PHILOSOPHERS 5
#define NUM_CHOPSTICKS 5

void dine(int n);


pthread_t philosopher[NUM_PHILOSOPHERS];
pthread_mutex_t chopstick[NUM_CHOPSTICKS];

int main()
{
// Define counter var i and status_message
int i, status_message;
void *msg;

// Initialise the semaphore array


for (i = 1; i <= NUM_CHOPSTICKS; i++)
{
status_message = pthread_mutex_init(&chopstick[i], NULL);
// Check if the mutex is initialised successfully
if (status_message == -1)
{
printf("\n Mutex initialization failed");
exit(1);
}
}

// Run the philosopher Threads using *dine() function


for (i = 1; i <= NUM_PHILOSOPHERS; i++)
{
status_message = pthread_create(&philosopher[i], NULL, (void *)dine, (int *)i);
if (status_message != 0)
{
printf("\n Thread creation error \n");
exit(1);
}
}

// Wait for all philosophers threads to complete executing (finish dining) before closing the
program
for (i = 1; i <= NUM_PHILOSOPHERS; i++)
{
status_message = pthread_join(philosopher[i], &msg);
if (status_message != 0)
{
printf("\n Thread join failed \n");
exit(1);
}
}

// Destroy the chopstick Mutex array


for (i = 1; i <= NUM_CHOPSTICKS; i++)
{
status_message = pthread_mutex_destroy(&chopstick[i]);
if (status_message != 0)
{
printf("\n Mutex Destroyed \n");
exit(1);
}
}
return 0;
}
void dine(int n)
{
printf("\nPhilosopher % d is thinking ", n);

// Philosopher picks up the left chopstick (wait)


pthread_mutex_lock(&chopstick[n]);

// Philosopher picks up the right chopstick (wait)


pthread_mutex_lock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);

// After picking up both the chopstick philosopher starts eating


printf("\nPhilosopher % d is eating ", n);
sleep(3);

// Philosopher places down the left chopstick (signal)


pthread_mutex_unlock(&chopstick[n]);

// Philosopher places down the right chopstick (signal)


pthread_mutex_unlock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);

// Philosopher finishes eating


printf("\nPhilosopher % d Finished eating ", n);
}
5.OUTPUT:-

6.RESULT:-

*Each philosopher alternates between thinking and eating.


*Forks are picked up and put down with mutual exclusion to avoid conflicts.
*The philosophers continue this cycle indefinitely in a way that avoids deadlock and starvation,
ensuring that all philosophers eventually get a chance to eat.
EXPERIMENT-3
1.OBJECTIVE:-

The objective of the Producer-Consumer Problem experiment is to synchronize the producer and
consumer processes using semaphores and mutexes. This ensures safe access to the shared buffer,
preventing race conditions and deadlock.

2.REQUIREMENT:-
Buffer: A shared data structure (usually an array or queue) that stores the items produced by the
producer and consumed by the consumer.
Semaphores: Semaphores (or mutexes) are used for synchronization between the producer and
consumer:
Threads: The producer and consumer are typically implemented as separate threads to allow
concurrent execution.
Synchronization Mechanisms: The system must synchronize the producer and consumer to
avoid accessing the buffer simultaneously and manage buffer overflow/underflow situations

3.PRODUCER-CONSUMER PROBLEM:-
The Producer-Consumer Problem involves two primary tasks:
1.Producer: The producer generates data and places it into the buffer. It can only produce if
there is space available in the buffer.
2.Consumer: The consumer takes data from the buffer and processes it. It can only consume if
the buffer is not empty.
Key Concepts:
3.Synchronization: The producer and consumer must synchronize their actions to avoid issues
such as race conditions, where both might try to access the buffer at the same time.
4.Semaphore/Mutex Usage:
.The Empty semaphore ensures that the producer waits if the buffer is full (no empty slots).
.The Full semaphore ensures that the consumer waits if the buffer is empty (no items to
consume).
.The Mutex ensures that the producer and consumer cannot access the buffer simultaneously,
preventing race conditions.
1.Buffer Management: The shared buffer must be managed in such a way that the producer does
not overwrite an item before the consumer consumes it, and the consumer does not try to
consume an item that hasn't been produced yet.

4.PROGRAM FOR PRODUCER-CONSUMER PROBLEM:-


// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
// Initialize a mutex to 1
int mutex = 1;
// Number of full slots as 0
int full = 0;
// Number of empty slots as size
// of buffer
int empty = 10, x = 0;
// Function to produce an item and
// add it to the buffer
void producer()
{
// Decrease mutex value by 1
--mutex;
// Increase the number of full
// slots by 1
++full;
// Decrease the number of empty
// slots by 1
--empty;
// Item produced
x++;
printf("\nProducer produces"
"item %d",
x);
// Increase mutex value by 1
++mutex;
}
// Function to consume an item and
// remove it from buffer
void consumer()
{
// Decrease mutex value by 1
--mutex;
// Decrease the number of full
// slots by 1
--full;
// Increase the number of empty
// slots by 1
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;
// Increase mutex value by 1
++mutex;
}
// Driver Code
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");
// Using '#pragma omp parallel for'
// can give wrong value due to
// synchronization issues.
// 'critical' specifies that code is
// executed by only one thread at a
// time i.e., only one thread enters
// the critical section at a given time
#pragma omp critical
for (i = 1; i > 0; i++) {
printf("\nEnter your choice:");
scanf("%d", &n);
// Switch Cases
switch (n) {
case 1:
// If mutex is 1 and empty
// is non-zero, then it is
// possible to produce
if ((mutex == 1)
&& (empty != 0)) {
producer();
}
// Otherwise, print buffer
// is full
else {
printf("Buffer is full!");
}
break;
case 2:
// If mutex is 1 and full
// is non-zero, then it is
// possible to consume
if ((mutex == 1)
&& (full != 0)) {
consumer();
}
// Otherwise, print Buffer
// is empty
else {
printf("Buffer is empty!");
}
break;
// Exit Condition
case 3:
exit(0);
break;
}
}
}

5.OUTPUT:-
EXPERIMENT-4
1.OBJECTIVE:-

The aim of this experiment is to implement the First Come, First Serve (FCFS) scheduling
algorithm in C language to demonstrate how processes are scheduled in the order of their arrival.
The experiment will focus on calculating metrics such as waiting time, turnaround time, and
completion time.

2.REQUIREMENT:-

i. Programming Language: C
ii. Input: Arrival time and burst time (execution time) of processes.
iii. Output: Completion time, waiting time, and turnaround time for each process.
iv. Tools: A C compiler (e.g., GCC).

3.FIRST COME FIRST SERVE ALGORITHM:-

The First Come, First Serve (FCFS) algorithm is one of the simplest CPU scheduling
algorithms. In FCFS:
• The process that arrives first gets executed first.
• If two processes arrive at the same time, the one that appears first in the input list is executed
first.
• FCFS is a non-preemptive algorithm, meaning once a process starts execution, it will run to
completion without being interrupted.
Formula:

1.Waiting Time (WT) for a process is the total time it has been in the ready queue waiting for
CPU time.
WT=Start Time−Arrival Time
2.Turnaround Time (TAT) is the total time spent from the arrival of a process to its completion.
TAT=Completion Time−Arrival Time
3.Completion Time (CT) is the time at which the process finishes its execution.
CT=Start Time + Burst Time

4.PROGRAM FOR FIRST COME FIRST SERVE ALGORITHM:-


#include <stdio.h>
int main()
{
int pid[15];
int bt[15];
int n;
printf("Enter the number of processes: ");
scanf("%d",&n);
printf("Enter process id of all the processes: ");
for(int i=0;i<n;i++)
{
scanf("%d",&pid[i]);
}
printf("Enter burst time of all the processes: ");
for(int i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
int i, wt[n];
wt[0]=0;
//for calculating waiting time of each process
for(i=1; i<n; i++)
{
wt[i]= bt[i-1]+ wt[i-1];
}
printf("Process ID Burst Time Waiting Time TurnAround Time\ n");
float twt=0.0;
float tat= 0.0;
for(i=0; i<n; i++)
{
printf("%d\t\t", pid[i]);
printf("%d\t\t", bt[i]);
printf("%d\t\t", wt[i]);
//calculating and printing turnaround time of each process
printf("%d\t\t", bt[i]+wt[i]);
printf("\n");
//for calculating total waiting time
twt += wt[i];
//for calculating total turnaround time
tat += (wt[i]+bt[i]);
}
float att,awt;
//for calculating average waiting time
awt = twt/n;

//for calculating average turnaround time


att = tat/n;
printf("Avg. waiting time= %f\n",awt);
printf("Avg. turnaround time= %f",att);
}
5.OUTPUT:-

6.RESULT:-

The First-Come-First-Served (FCFS) algorithm is a basic and fair scheduling approach but is not
optimal for performance, especially when there is a large difference in burst times of processes. It
can lead to high waiting times for shorter processes if long processes arrive first. However, it
remains widely used in simple systems and in scenarios where fairness and simplicity are more
important than optimal CPU utilization.
EXPERIMENT-5
1.OBJECTIVE:-

The aim of this experiment is to implement the Shortest Job First (SJF) scheduling algorithm in
C, which selects the process with the shortest burst time for execution. The goal is to calculate
and display the waiting time, turnaround time, and completion time for each process.

2.REQUIREMENTS:-

1. Programming Language: C
2. Input:
o Number of processes.
o Arrival time and burst time (execution time) of each process.
3. Output:
o Process ID, Arrival Time, Burst Time, Completion Time, Waiting Time, and
Turnaround Time for each process.
4. Tools: C compiler (e.g., GCC).

3.SJF ALGORITHM:-

The Shortest Job First (SJF) scheduling algorithm selects the process with the shortest burst time
for execution. If two processes have the same burst time, FCFS (First-Come-First-Serve) can be
used as a tie-breaker. SJF is considered optimal because it minimizes the average waiting time.
However, it requires knowing the burst times of processes in advance, which is not always
feasible.
Key Terminology:
1.Burst Time: The time required by a process for execution.
2.Waiting Time: The total time a process has spent waiting in the ready queue.
WT=Start Time−Arrival Time
3.Turnaround Time: The total time spent by the process from its arrival to its completion.
TAT=Completion Time−Arrival Time
4.Completion Time: The time at which the process finishes its execution.

The SJF algorithm is non-preemptive, meaning once a process starts executing, it runs to
completion without being interrupted.

4.PROGRAM FOR SJF ALGORITHM:-


#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,totalT=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1;
}
//sorting of burst times
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0;
//finding the waiting time of all the processes
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
//individual WT by adding BT of all previous completed processes
wt[i]+=bt[j];
//total waiting time
total+=wt[i];
}
//average waiting time
avg_wt=(float)total/n;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
//turnaround time of individual processes
tat[i]=bt[i]+wt[i];
//total turnaround time
totalT+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
//average turnaround time
avg_tat=(float)totalT/n;
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f",avg_tat);
}
5.OUTPUT:-

6.RESULT:-

The First-Come-First-Served (FCFS) algorithm is a basic and fair scheduling approach but is not
optimal for performance, especially when there is a large difference in burst times of processes. It
can lead to high waiting times for shorter processes if long processes arrive first. However, it
remains widely used in simple systems and in scenarios where fairness and simplicity are more
important than optimal CPU utilization.
EXPRIMENT-6
1.OBJECTIVE:-

The aim of this experiment is to implement the Round Robin (RR) scheduling algorithm in C,
where processes are assigned a fixed time quantum for execution. The goal is to calculate and
display the waiting time, turnaround time, and completion time for each process.

2.REQUIREMENT:-

Programming Language: C
Input:
• Number of processes.
• Arrival time and burst time (execution time) for each process.
• Time quantum (time slice).
Output:
• Process ID, Arrival Time, Burst Time, Completion Time, Waiting Time, and Turnaround
Time for each process.
Tools: C compiler (e.g., GCC).

3.ROUND ROBIN ALGORITHM:-

Round Robin is a CPU scheduling algorithm where each process is assigned a fixed time slot in a
cyclic way. It is basically the preemptive version of First come First Serve CPU Scheduling
algorithm.
1 . Round Robin CPU Algorithm generally focuses on Time Sharing technique.
2.The period of time for which a process or job is allowed to run in a
pre-emptive method is called time quantum.
3.Each process or job present in the ready queue is assigned the CPU for that time quantum, if
the execution of the process is completed during that time then the process will end else the
process will go back to the waiting table and wait for its next turn to complete the execution.
Key Metrics:
• Waiting Time (WT): The time a process spends waiting in the ready queue before it gets
the CPU.
WT=Turnaround Time−Burst Time
• Turnaround Time (TAT): The total time from the arrival of a process to its completion.
TAT=Completion Time−Arrival Time
• Completion Time (CT): The time at which the process finishes its execution.

4.PROGRAM FOR ROUND ROBIN ALGORITHM:-


#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
struct P
{
int AT, BT, ST[20], WT, FT, TAT, pos;
};

int quant;
int main()
{
int n, i, j;
// Taking Input
printf("Enter the no. of processes :");
scanf("%d", &n);
struct P p[n];
printf("Enter the quantum \n");
scanf("%d", &quant);
printf("Enter the process numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &(p[i].pos));
printf("Enter the Arrival time of processes \n");
for (i = 0; i < n; i++)
scanf("%d", &(p[i].AT));

printf("Enter the Burst time of processes \n");


for (i = 0; i < n; i++)
scanf("%d", &(p[i].BT));

// Declaring variables
int c = n, s[n][20];
float time = 0, mini = INT_MAX, b[n], a[n];

// Initializing burst and arrival time arrays


int index = -1;
for (i = 0; i < n; i++)
{
b[i] = p[i].BT;
a[i] = p[i].AT;
for (j = 0; j < 20; j++)
{
s[i][j] = -1;
}
}

int tot_wt, tot_tat;


tot_wt = 0;
tot_tat = 0;
bool flag = false;
while (c != 0)
{
mini = INT_MAX;
flag = false;

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


{
float p = time + 0.1;
if (a[i] <= p && mini > a[i] && b[i] > 0)
{
index = i;
mini = a[i];
flag = true;
}
}
// if at =1 then loop gets out hence set flag to false
if (!flag)
{
time++;
continue;
}
// calculating start time
j = 0;

while (s[index][j] != -1)


{
j++;
}
if (s[index][j] == -1)
{
s[index][j] = time;
p[index].ST[j] = time;
}

if (b[index] <= quant)


{
time += b[index];
b[index] = 0;
}
else
{
time += quant;
b[index] -= quant;
}

if (b[index] > 0)
{
a[index] = time + 0.1;
}
// calculating arrival,burst,final times
if (b[index] == 0)
{
c--;
p[index].FT = time;
p[index].WT = p[index].FT - p[index].AT - p[index].BT;
tot_wt += p[index].WT;
p[index].TAT = p[index].BT + p[index].WT;
tot_tat += p[index].TAT;
}

} // end of while loop


// Printing output
printf("Process number ");
printf("Arrival time ");
printf("Burst time ");
printf("\tStart time");
j = 0;
while (j != 10)
{
j += 1;
printf(" ");
}
printf("\t\tFinal time");
printf("\tWait Time ");
printf("\tTurnAround Time \n");
for (i = 0; i < n; i++)
{
printf("%d \t\t", p[i].pos);
printf("%d \t\t", p[i].AT);
printf("%d \t", p[i].BT);
j = 0;
int v = 0;
while (s[i][j] != -1)
{
printf("%d ", p[i].ST[j]);
j++;
v += 3;
}
while (v != 40)
{
printf(" ");
v += 1;
}
printf("%d \t\t", p[i].FT);
printf("%d \t\t", p[i].WT);
printf("%d \n", p[i].TAT);
}
// Calculating average wait time and turnaround time
double avg_wt, avg_tat;
avg_wt = tot_wt / (float)n;
avg_tat = tot_tat / (float)n;
// Printing average wait time and turnaround time
printf("The average wait time is : %lf\n", avg_wt);
printf("The average TurnAround time is : %lf\n", avg_tat);
return 0;
}
5.OUTPUT:-

6.RESULT:-

The Round Robin algorithm is suitable for time-sharing systems where all processes are
considered equally important and should be given a fair share of CPU time. However, the
efficiency of the algorithm is not optimal for processes with very different burst times.
EXPRIMENT-7
1.OBJECTIVE:-

The aim of this experiment is to implement the Priority Scheduling algorithm in C, where
processes are executed based on their priority. The goal is to calculate and display the waiting
time, turnaround time, and completion time for each process based on their assigned priority.

2.REQUIREMENTS:-

Programming Language: C
Input:
• Number of processes.
• Arrival time, burst time (execution time), and priority of each process.
Output:
• Process ID, Arrival Time, Burst Time, Priority, Completion Time, Waiting Time, and
Turnaround Time for each process.
Tools: C compiler (e.g., GCC).

3.PRIORITY SCHEDULING ALGORITHM:-

The Priority Scheduling algorithm is used to schedule processes in a manner where each process
is assigned a priority value. The key idea is that the process with the highest priority (usually
represented by the lowest numerical value) is executed first.
• Non-preemptive: Once a process starts executing, it runs to completion without being
interrupted.
• Preemptive version: In the preemptive version (also known as Preemptive Priority
Scheduling), a process with a higher priority can preempt a running process with a lower
priority.
Key Metrics:
• Waiting Time (WT): The total time a process spends in the ready queue before getting
CPU time.
WT=Turnaround Time−Burst Time
• Turnaround Time (TAT): The total time a process takes from its arrival to its completion.
TAT=Completion Time−Arrival Time
• Completion Time (CT): The time at which the process finishes execution.

4.PROGRAM FOR PRIORITY SCHEDULING ALGORITHM:-


#include <stdio.h>
//Function to swap two variables
void swap(int a,int b)
{
int temp=a;
a=b;
b=temp;
}
int main()
{
int n;
printf("Enter Number of Processes: ");
scanf("%d",&n);
// b is array for burst time, p for priority and index for process id
int b[n],p[n],index[n];
for(int i=0;i<n;i++)
{
printf("Enter Burst Time and Priority Value for Process %d: ",i+1);
scanf("%d %d",&b[i],&p[i]);
index[i]=i+1;
}
for(int i=0;i<n;i++)
{
int a=p[i],m=i;
position
}
//Finding out highest priority element and placing it at its desired
for(int j=i;j<n;j++)
{
if(p[j] > a)
{
a=p[j];
m=j;
}
}
//Swapping processes
swap(&p[i], &p[m]);
swap(&b[i], &b[m]);
swap(&index[i],&index[m]);
// T stores the starting time of process
int t=0;
//Printing scheduled process
printf("Order of process Execution is\n");
for(int i=0;i<n;i++)
{
printf("P%d is executed from %d to %d\n",index[i],t,t+b[i]);
t+=b[i];
}
printf("\n");
printf("Process Id
Burst Time
Wait Time
TurnAround Time\n");
int wait_time=0;
for(int i=0;i<n;i++)
{
printf("P%d
%d
%d
%d\
n",index[i],b[i],wait_time,wait_time + b[i]);
wait_time += b[i];
}
return 0;
}

5.OUTPUT:-

6.RESULT:-

1.The Priority Scheduling Algorithm ensures that processes with the highest priority (lowest
priority number) are executed first, which may lead to starvation for low-priority processes.
2.The Average Waiting Time and Average Turnaround Time are calculated to evaluate the
performance,
EXPERIMENT-8
1.OBJECTIVE:-

The objective of this program is to implement the Banker's Algorithm for Deadlock Avoidance in
an operating system. The Banker's Algorithm is used to determine whether the system is in a safe
state or not by analyzing the allocation of resources and processes. The program will simulate
resource allocation and determine if a deadlock will occur or if the system is in a safe state.

2.REQUIREMENT:-

Hardware Requirements:
• Computer or Workstation: Any machine with a functioning operating system.
• Memory: Sufficient memory to run the program and store data for multiple processes and
resources.
Software Requirements:
• C Compiler: GCC, Clang, or any C IDE (e.g., Visual Studio).
• Operating System: Any modern OS (Windows, Linux, macOS).
• Libraries: Standard C library (stdio.h, stdlib.h).

3.BANKER’S ALGORITHM:-

The Banker's Algorithm is a deadlock avoidance algorithm used in operating systems. It


operates by checking if a process can proceed without causing deadlock. The system is considered
in a safe state if there exists at least one sequence of processes such that each process can obtain
its maximum resources, execute, and release the resources. If the system cannot guarantee this, it
is in an unsafe state, and deadlock may occur.
Components:
1. Allocation Matrix (Allocation[i][j]): Indicates the number of resources of type j allocated
to process i.
2. Maximum Matrix (Maximum[i][j]): Indicates the maximum number of resources of type
j needed by process i.
3. Available Vector (Available[j]): Indicates the number of available resources of type j in the
system.
4. Need Matrix (Need[i][j]): The remaining resources that process i needs, which is
calculated as:
Need[i][j]=Maximum[i][j]−Allocation[i][j]
This matrix tells us how many resources of each type each process still requires.
Banker's Algorithm Process:
1. Safety Check: The algorithm checks if there is a sequence of processes that can finish
without causing deadlock.
2. Resource Request: When a process requests resources, the system checks if granting the
request will result in a safe state. If yes, resources are allocated; otherwise, the request is
denied.
Conditions for Safe State:
1. A system is in a safe state if there is a sequence of processes such that each process can
receive its maximum request without causing a deadlock.
2. If a process can finish, it will release all resources, making them available for other
processes.

4.PROGRAM FOR BANKER’S ALGORITHM:-


#include <stdio.h>
int main()
{
int n, m, i, j, k;
n = 5;
m = 3;
int alloc[5][3] = { { 0, 1, 0 },
{ 2, 0, 0 },
{ 3, 0, 2 },
{ 2, 1, 1 },
{ 0, 0, 2 } };
int max[5][3] = { { 7, 5, 3 },
{ 3, 2, 2 },
{ 9, 0, 2 },
{ 2, 2, 2 },
{ 4, 3, 3 } };
int avail[3] = { 3, 3, 2 };
int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++)
{
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++)
{
for (i = 0; i < n; i++)
{
if (f[i] == 0)
{
int flag = 0;
for (j = 0; j < m; j++)
{
if (need[i][j] > avail[j])
{
flag = 1;
break;
}
}
if (flag == 0)
{
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
return 0;
}

5.INPUT:-

6.OUTPUT:-
EXPRIMENT-9
1.OBJECTIVE:-

The objective of this program is to simulate and demonstrate the concepts of external and internal
fragmentation in memory management. The program will simulate memory allocation and
deallocation, illustrating how fragmentation occurs when memory is allocated in an inefficient
way. The program will also show how memory is wasted both inside allocated blocks (internal
fragmentation) and outside allocated blocks (external fragmentation).

2.REQUIREMENTS:-

Hardware Requirements:

Computer or Workstation: Any machine with a functioning operating system (Windows,


macOS, or Linux).
Memory: Sufficient RAM to run the program.

Software Requirements:

C Compiler: GCC, Clang, or any C IDE (e.g., Visual Studio).


Operating System: Any modern OS (Windows, Linux, macOS).
Libraries: Standard C library (stdio.h, stdlib.h).

3.FRAGMENTATION:-

External Fragmentation:
External fragmentation occurs when free memory is scattered in small blocks between allocated
blocks. Although there may be enough total free memory to satisfy a request, it cannot be
allocated as a contiguous block because of gaps between allocated blocks. This makes it impossible
to allocate larger memory blocks, even if the total free memory is sufficient.
Internal Fragmentation:
Internal fragmentation happens when memory is allocated in fixed-size blocks. If a block is larger
than what is actually needed, the remaining unused space inside the block is wasted. This unused
space is called internal fragmentation, and it typically happens when memory is allocated in units
of a fixed size, and the process doesn't use all the memory within the block.

4.PROGRAM FOR FRAGMENTATION :-


#include <stdio.h>
#include <stdlib.h>
main()
{
int ms, mp[10], i,
temp, n = 0;
char ch = 'y';
printf("\nEnter the total memory available (in Bytes)-- ");
scanf("%d", &ms);
temp = ms;
for (i = 0; ch == 'y'; i++, n++)
{
printf("\nEnter memory required for process %d (in Bytes) --
", i + 1);
scanf("%d", &mp[i]);
if (mp[i] <= temp)
{
printf("\nMemory is allocated for Process %d ", i + 1);
temp = temp - mp[i];
}
else
{
printf("\nMemory is Full");
break;
}
printf("\nDo you want to continue(y/n) -- ");
scanf(" %c", &ch);
}
printf("\n\nTotal Memory Available -- %d", ms);
printf("\n\n\tPROCESS\t\t MEMORY ALLOCATED ");
for (i = 0; i < n; i++)
printf("\n \t%d\t\t%d", i + 1, mp[i]);
printf("\n\nTotal Memory Allocated is %d", ms - temp);
printf("\nTotal External Fragmentation is %d", temp);
}

5.OUTPUT:-

You might also like