You are on page 1of 72

COMPUTER LABORATORY MANUAL

OPERATING SYSTEMS
(CSC-202)

Prepared By:

Ms. Shiza Riaz Memon

Computer Science Department


Sindh Madressatul Islam University, Aiwan-e-Tijarat Road,
Karachi
http://www.smiu.edu.pk
CERTIFICATE

DEPARTMENT OF COMPUTER SCIENCE


OPERATING SYSTEMS (CSC-202)

This is to certify that Mr/Ms. So/Do


having Roll No. has successfully
completed laboratory work during Spring Semester 2022.

Course Supervisor: Lab. Instructor


Ms.Shiza Riaz Memon Imtiaz Hussain

Signature: Signature:
Operating Systems Lab Manual

Lab No: Index Sign

1 Introduction to Operating Systems

2 Write a C program to simulate the following CPU scheduling algorithms to


find turnaround time and waiting time.
a)FCFS b)SJF c)Round Robin d)Priority

3 Write a C program to illustrate simultaneous execution of two or more threads

Write a C program to simulate producer-consumer problem using semaphores.


4

Write a C program to simulate the concept of Readers-Writers problem.


5

*Write a C program to simulate the concept of Dining-Philosophers problem.


6

7 Write a C program to simulate Bankers algorithm for the purpose of deadlock


avoidance

8 Write a C Program to implement the deadlock detection

Write a C program to simulate the following contiguous memory allocation


9
techniques

a) Worst-fit b) Best-fit c) First-fit

10 Write a C program to simulate paging technique of memory management

11 Write a C Program to simulate segmentation technique of memory


management

Sindh Madressatul Islam University


Operating Systems Lab Manual

Write a C program to simulate page replacement algorithms


12
a) FIFO b) LRU c) Optimal d)MRU
Write a C program to simulate disk scheduling algorithms
13
a) FCFS b) SSTF c) SCAN

14 Write a C program to simulate the following file allocation strategies.


a) Sequential b) Indexed c) Linked

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 1

INTRODUCTION TO OPERATING SYSTEMS

Objective: To get familiarized with the basics of operating systems

Operating System: It supports computer's basic functions as shown in Figure 1.1

What tasks an OS Perform?

• Processor management.
• Memory management
• Device management
• Application.
• Storage management
• Application interface
• User interface

Types of OS
• Linux
• Windows 8, Windows 7, Vista, XP
• Mac

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 2

PROCESS SCHEDULING ALGORITHMS

Objective: Write a C program to simulate the following CPU scheduling algorithms to find turnaround

time and waiting time for the above problem.

a) FCFS b) SJF c) Round Robin d) Priority

a) FCFS CPU SCHEDULING ALGORITHM


For FCFS scheduling algorithm, read the number of processes/jobs in the system, their CPU burst
times. The scheduling is performed on the basis of arrival time of the processes irrespective of their
other parameters. Each process will be executed according to its arrival time. Calculate the waiting
time and turnaround time of each of the processes accordingly.

Program:

#include<stdio.h>
#include<conio.h>
main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
clrscr();
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i); scanf("%d",&bt[i]);
}
wt[0] = wtavg = 0; tat[0] =
tatavg = bt[0]; for(i=1;i<n;i++)
{

Sindh Madressatul Islam University


Operating Systems Lab Manual

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


+bt[i]; wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n); printf("\nAverage Turnaround Time --
%f", tatavg/n);
getch();

OUTPUT:

b) SJF CPU SCHEDULING ALGORITHM


For SJF scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times.
Arrange all the jobs in order with respect to their burst times. There may be two jobs in queue with the
same execution time, and then FCFS approach is to be performed. Each process will be executed
according to the length of its burst time. Then calculate the waiting time and turnaround time of each

Sindh Madressatul Islam University


Operating Systems Lab Manual

of the processes accordingly.

Program:

#include <stdio.h>
#include <conio.h>
main()
{

int p[20], bt[20], wt[20], tat[20], i, k, n, temp; float wtavg, tatavg;


clrscr();
printf("\nEnter the number of processes -- "); scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0; tat[0] = tatavg = bt[0]; for(i=1;i<n;i++)
{

wt[i] = wt[i-1] +bt[i-1];

Sindh Madressatul Islam University


Operating Systems Lab Manual

tat[i] = tat[i-1] +bt[i]; wtavg = wtavg + wt[i];


tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME”);
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]); printf("\nAverage Waiting Time --
%f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();

OUTPUT:

Sindh Madressatul Islam University


Operating Systems Lab Manual

c) ROUND ROBIN CPU SCHEDULING ALGORITHM


For round robin scheduling algorithm, read the number of processes/jobs in the system, their CPU burst
times, and the size of the time slice. Time slices are assigned to each process in equal portions and in
circular order, handling all processes execution. This allows every process to get an equal chance.
Calculate the waiting time and turnaround time of each of the processes accordingly.

Program:

#include <stdio.h>
#include <conio.h>
main()
{

int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
clrscr();
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 time quantum -- ");
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];
Sindh Madressatul Islam University
Operating Systems Lab Manual

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]); getch();
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

OUTPUT:

d) PRIORITY CPU SCHEDULING ALGORITHM


For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst
times, and the priorities. Arrange all the jobs in order with respect to their priorities. There may be two
jobs in queue with the same priority, and then FCFS approach is to be performed. Each process will be
executed according to its priority. Calculate the waiting time and turnaround time of each of the
processes accordingly.

Program:

#include <stdio.h>
#include <conio.h>
main()
{

Sindh Madressatul Islam University


Operating Systems Lab Manual

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++)
{
Sindh Madressatul Islam University
Operating Systems Lab Manual

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);
getch();
}

OUTPUT:

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 3

THREADS

Objective: Write a C program to illustrate simultaneous execution of two or more threads

THREADS:

A thread is a single sequence stream within a process. Threads are executed within a process. They
are sometimes called lightweight processes. In a process, threads allow multiple executions of streams.
Threads are popular way to improve application through parallelism. The CPU switches rapidly back
and forth among the threads giving illusion that the threads are running in parallel. Like a traditional
process i.e., process with one thread, a thread can be in any of several states (Running, Blocked,
Ready or terminated).

Program:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2; char
*message1 = "Thread 1"; char
*message2 = "Thread 2";
int iret1, iret2;

/* Create independent threads each of which will execute function */

iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2


= pthread_create( &thread2, NULL, print_message_function, (void*) message2);

/* Wait till threads are complete before main continues. Unless we */

Sindh Madressatul Islam University


Operating Systems Lab Manual

/* wait we run the risk of executing an exit which will terminate */


/* the process and all threads before the threads have completed. */

pthread_join( thread1, NULL);


pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2); exit(0);
}
void *print_message_function( void *ptr )
{
char *message; message
= (char *) ptr; printf("%s
\n", message);
}
Compile: gcc –pthread –o a mt.c
Run:./a.out

OUTPUT :

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No. 4
PROCESS SYNCHRONIZATION

Objective: Write a C program to simulate producer-consumer problem using semaphores.


PRODUCER CONSUMER PROBLEM:
Producer-consumer problem, is a common paradigm for cooperating processes. A producer process
produces information that is consumed by a consumer process. One solution to the producer-consumer
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.
A producer can produce one item while the consumer is consuming another item. 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>
void 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 \t3. Exit”);
printf(“\nEnter your choice: ”);
scanf(“%d”, &choice);
switch(choice) {
case 1: if((in+1)%bufsize==out)
printf(“\nBuffer is Full”);

Sindh Madressatul Islam University


Operating Systems Lab Manual

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;

}}}

OUTPUT:

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No. 5
PROCESS SYNCHRONIZATION

Objective: Write a C program to simulate readers writers problem using semaphores.

READERS-WRITERS PROBLEM:
In cooperating processes there is a shared resource which should be accessed by multiple processes.
There are two types of processes in this context. They are reader and writer. Any number
of readers can read from the shared resource simultaneously, but only one writer can write to the
shared resource. When a writer is writing data to the resource, no other process can access the
resource. A writer cannot write to the resource if there are non zero number of readers accessing the
resource at that time.

Program:

#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
sem_t x,y;
pthread_t tid;
pthread_t writerthreads[100],readerthreads[100];
int readercount = 0;

void *reader(void* param)


{
sem_wait(&x);
readercount++;

Sindh Madressatul Islam University


Operating Systems Lab Manual

if(readercount==1)

sem_wait(&y);
sem_post(&x);
printf("%d reader is inside\n",readercount);
usleep(3);
sem_wait(&x);
readercount--;
if(readercount==0)
{
sem_post(&y);
}
sem_post(&x);
printf("%d Reader is leaving\n",readercount+1);
return NULL;
}

void *writer(void* param)


{
printf("Writer is trying to enter\n");
sem_wait(&y);
printf("Writer has entered\n");
sem_post(&y);
printf("Writer is leaving\n");
return NULL;
}
int main()
{
int n2,i;
printf("Enter the number of readers:");

Sindh Madressatul Islam University


Operating Systems Lab Manual

scanf("%d",&n2);
printf("\n");
int n1[n2];
sem_init(&x,0,1);
sem_init(&y,0,1);
for(i=0;i<n2;i++)
{
pthread_create(&writerthreads[i],NULL,reader,NULL);
pthread_create(&readerthreads[i],NULL,writer,NULL);
}
for(i=0;i<n2;i++)
{
pthread_join(writerthreads[i],NULL);
pthread_join(readerthreads[i],NULL);
}
}
OUTPUT:

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No. 6
PROCESS SYNCHRONIZATION

Objective: Write a C program to simulate the concept of Dining Philosopher’s Problem

DINING PHILOSOPHERS PROBLEM:


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>
#define n 4
int compltedPhilo = 0,i;
struct fork{
int taken;
}ForkAvil[n];
struct philosp{
int left;
int right;
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

Philostatus[n];
void goForDinner(int philID){ //same like threads
concept here cases implemented
if(Philostatus[philID].left==10 &&
Philostatus[philID].right==10)
printf("Philosopher %d completed his
dinner\n",philID+1);
//if already completed dinner
else if(Philostatus[philID].left==1 &&
Philostatus[philID].right==1){
//if just taken two forks
printf("Philosopher %d completed his
dinner\n",philID+1);

Philostatus[philID].left =
Philostatus[philID].right = 10; //remembering that he
completed dinner by assigning value 10
int otherFork = philID-1;

if(otherFork== -1)
otherFork=(n-1);

ForkAvil[philID].taken =
ForkAvil[otherFork].taken = 0; //releasing forks
printf("Philosopher %d released fork %d and
fork %d\n",philID+1,philID+1,otherFork+1);
compltedPhilo++;
}
else if(Philostatus[philID].left==1 &&
Philostatus[philID].right==0){ //left already taken,
trying for right fork
if(philID==(n-1)){

Sindh Madressatul Islam University


Operating Systems Lab Manual

if(ForkAvil[philID].taken==0){ //KEY
POINT OF THIS PROBLEM, THAT LAST
PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID].taken =
Philostatus[philID].right = 1;
printf("Fork %d taken by philosopher
%d\n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for
fork %d\n",philID+1,philID+1);
}
}else{ //except last philosopher case
int dupphilID = philID;
philID-=1;

if(philID== -1)
philID=(n-1);

if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken =
Philostatus[dupphilID].right = 1;
printf("Fork %d taken by Philosopher
%d\n",philID+1,dupphilID+1);
}else{
printf("Philosopher %d is waiting for
Fork %d\n",dupphilID+1,philID+1);
}
}
}
else if(Philostatus[philID].left==0){ //nothing
taken yet
if(philID==(n-1)){
Sindh Madressatul Islam University
Operating Systems Lab Manual

if(ForkAvil[philID-1].taken==0){ //KEY
POINT OF THIS PROBLEM, THAT LAST
PHILOSOPHER TRYING IN reverse DIRECTION
ForkAvil[philID-1].taken =
Philostatus[philID].left = 1;
printf("Fork %d taken by philosopher
%d\n",philID,philID+1);
}else{
printf("Philosopher %d is waiting for
fork %d\n",philID+1,philID);
}
}else{ //except last philosopher case
if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken =
Philostatus[philID].left = 1;
printf("Fork %d taken by Philosopher
%d\n",philID+1,philID+1);
}else{
}
}
}else{}
}

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

ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right
=0;
while(compltedPhilo<n){
/* Observe here carefully, while loop will run until all
philosophers complete dinner
Actually problem of deadlock occur only thy try to take

Sindh Madressatul Islam University


Operating Systems Lab Manual

at same time. This for loop will say that they are trying
at same time. And remaining status will print by go for
dinner function
*/
for(i=0;i<n;i++)
goForDinner(i);
printf("\nTill now num of philosophers completed
dinner are %d\n\n",compltedPhilo);
}

return 0;
}
printf("Philosopher %d is waiting for
Fork %d\n",philID+1,philID+1);

OUTPUT:

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No. 7
BANKER’S ALGORITHM
BANKER’S ALGORITHM:
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests for safety
by simulating the allocation for predetermined maximum possible amounts of all resources, then makes
an “s-state” check to test for possible activities, before deciding whether allocation should be allowed to
continue.
Program:
#include <stdio.h>
int current[5][5], maximum_claim[5][5], available[5];
int allocation[5] = {0, 0, 0, 0, 0};
int maxres[5], running[5], safe = 0;
int counter = 0, i, j, exec, resources, processes, k = 1;

int main()
{
printf("\nEnter number of processes: ");
scanf("%d", &processes);
for (i = 0; i < processes; i++)
{
running[i] = 1;
counter++;
}
printf("\nEnter number of resources: ");
scanf("%d", &resources);

printf("\nEnter Claim Vector:");


for (i = 0; i < resources; i++)
{
scanf("%d", &maxres[i]);

Sindh Madressatul Islam University


Operating Systems Lab Manual

}
printf("\nEnter Allocated Resource Table:\n");
for (i = 0; i < processes; i++)
{
for(j = 0; j < resources; j++)
{
scanf("%d", &current[i][j]);
}
}
printf("\nEnter Maximum Claim Table:\n");
for (i = 0; i < processes; i++)
{
for(j = 0; j < resources; j++)
{
scanf("%d", &maximum_claim[i][j]);
}
}
printf("\nThe Claim Vector is: ");
for (i = 0; i < resources; i++)
{
printf("\t%d", maxres[i]);
}
printf("\nThe Allocated Resource Table:\n");
for (i = 0; i < processes; i++)
{
for (j = 0; j < resources; j++)
{
printf("\t%d", current[i][j]);
}
printf("\n");
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

printf("\nThe Maximum Claim Table:\n");


for (i = 0; i < processes; i++)
{
for (j = 0; j < resources; j++)
{
printf("\t%d", maximum_claim[i][j]);
}
printf("\n");
}
for (i = 0; i < processes; i++)
{
for (j = 0; j < resources; j++)
{
allocation[j] += current[i][j];
}
}
printf("\nAllocated resources:");
for (i = 0; i < resources; i++)
{
printf("\t%d", allocation[i]);
}

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


{
available[i] = maxres[i] - allocation[i];
}
printf("\nAvailable resources:");
for (i = 0; i < resources; i++)
{
printf("\t%d", available[i]);
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

printf("\n");
while (counter != 0)
{
safe = 0;
for (i = 0; i < processes; i++)
{
if (running[i])
{
exec = 1;
for (j = 0; j < resources; j++)
{
if (maximum_claim[i][j] - current[i][j] > available[j])
{
exec = 0;
break;
}
}
if (exec)
{
printf("\nProcess%d is executing\n", i + 1);
running[i] = 0;
counter--;
safe = 1;
for (j = 0; j < resources; j++)
{
available[j] += current[i][j];
}
break;
}
}
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

if (!safe)
{
printf("\nThe processes are in unsafe state.\n");
break;
}
else
{
printf("\nThe process is in safe state");
printf("\nAvailable vector:");

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


{
printf("\t%d", available[i]);
}

printf("\n");
}
}
return 0;

Sindh Madressatul Islam University


Operating Systems Lab Manual

OUTPUT:

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 8
DEADLOCK
Objective: Write a C program to implement the deadlock detection
DEADLOCK:
A deadlock exists in the system if and only if there is a cycle in the wait-for graph. In order to
detect the deadlock, the system needs to maintain the wait-for graph and periodically system invokes
an algorithm that searches for the cycle in the wait-for graph.
Program:
#include <stdio.h>
#include <conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n,r;
void input();
void show();
void cal();
int main()
{
int i,j;
printf("********** Deadlock Detection Algo ************\n");
input();
show();
cal();
getch();
return 0;
}
void input()
{
int i,j;

Sindh Madressatul Islam University


Operating Systems Lab Manual

printf("Enter the no of Processes\t");


scanf("%d",&n);
printf("Enter the no of resource instances\t");
scanf("%d",&r);
printf("Enter the Max Matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&max[i][j]);
}
}
printf("Enter the Allocation Matrix\n"); for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&alloc[i][j]);
}
}
printf("Enter the available Resources\n"); for(j=0;j<r;j++)
{
scanf("%d",&avail[j]);
}
}
void show()
{ int i,j;
printf("Process\t Allocation\t Max\t Available\t"); for(i=0;i<n;i++)
{
printf("\nP%d\t ",i+1); for(j=0;j<r;j++)
{
printf("%d ",alloc[i][j]);
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

printf("\t");
for(j=0;j<r;j++)
{
printf("%d ",max[i][j]);
}
printf("\t");
if(i==0)
{
for(j=0;j<r;j++)
printf("%d ",avail[j]);
}
}
}
void cal()
{
int finish[100],temp,need[100][100],flag=1,k,c1=0; int dead[100]; int
safe[100]; int i,j; for(i=0;i<n;i++)
{
finish[i]=0;
}
//find need matrix
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}
}
while(flag)
{
flag=0;
for(i=0;i<n;i++)
Sindh Madressatul Islam University
Operating Systems Lab Manual

{
int c=0;
for(j=0;j<r;j++)
{
if((finish[i]==0)&&(need[i][j]<=avail[j]))
{
c++;
if(c==r)
{
for(k=0;k<r;k++)

avail[k]+=alloc[i][j]; finish[i]=1;
flag=1;
}

//printf("\nP%d",i);
if(finish[i]==1)
{

i=n;

}
}
}
}
}
j=0; flag=0;
for(i=0;i<n;i
++)
{
if(finish[i]==0)
{

Sindh Madressatul Islam University


Operating Systems Lab Manual

dead[j]=i
; j++;
flag=1;
}
}
if(flag==1)
{
printf("\n\nSystem is in Deadlock and the Deadlock process are\n");
for(i=0;i<n;i++)
{
}
}
else
{
printf("P%d\t",dead[i]);

}
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 9
MEMORY ALLOCATION TECHNIQUES

Objective: Write a C program to simulate the following contiguous memory allocation techniques
a) Worst-fit b) Best-fit c) First-fit

 Worst fit: The memory manager places a process in the largest block of unallocated memory
available. The idea is that this placement will create the largest hold after the allocations, thus
increasing the possibility that, compared to best fit, another process can use the remaining space.
Using the same example as above, worst fit will allocate 12KB of the 19KB block to the process,
leaving a 7KB block for future use.

 Best fit: The allocator places a process in the smallest block of unallocated memory in which it will
fit. For example, suppose a process requests 12KB of memory and the memory manager currently has
a list of unallocated blocks of 6KB, 14KB, 19KB, 11KB, and 13KB blocks. The best-fit strategy will
allocate 12KB of the 13KB block to the process.

 First fit: There may be many holes in the memory, so the operating system, to reduce the amount of
time it spends analyzing the available spaces, begins at the start of primary memory and allocates
memory from the first hole it encounters large enough to satisfy the request. Using the same example
as above, first fit will allocate 12KB of the 14KB block to the process.

Program:

#include<stdio.h> main()

int p[10],np,b[10],nb,ch,c[10],d[10],alloc[10],flag[10],i,j;
printf("\nEnter the no of process:"); scanf("%d",&np);
printf("\nEnter the no of blocks:"); scanf("%d",&nb);
printf("\nEnter the size of each process:");
for(i=0;i<np;i++)
{

printf("\nProcess %d:",i); scanf("%d",&p[i]);


}
printf("\nEnter the block sizes:"); for(j=0;j<nb;j++)

Sindh Madressatul Islam University


Operating Systems Lab Manual

printf("\nBlock %d:",j); scanf("%d",&b[j]);c[j]=b[j];d[j]=b[j];


}

if(np<=nb)

printf("\n1.First fit 2.Best fit 3.Worst fit"); do


{

printf("\nEnter your choice:");


scanf("%d",&ch); switch(ch)
{

case 1: printf("\nFirst Fit\n"); for(i=0;i<np;i++)


{

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

if(p[i]<=b[j])

alloc[j]=p[i];printf("\n\nAlloc[%d]",all
oc[j]);

printf("\n\nProcess %d of size %d is
allocated in block:%d of size:%d",i,p[i],j,b[j]);
flag[i]=0,b[j]=0;break;
}

else
flag[i
]=1;
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

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

if(flag[i]!=0)

printf("\n\nProcess %d of size %d is not


allocated",i,p[i]);

break;

case 2: printf("\nBest Fit\n"); for(i=0;i<nb;i++)


{

for(j=i+1;j<nb;j++)

{ if(c[i]>c[j])
{

int temp=c[i];
c[i]=c[j];
c[j]=temp;
}

printf("\nAfter sorting block sizes:");


for(i=0;i<nb;i++) printf("\nBlock
%d:%d",i,c[i]); for(i=0;i<np;i++)
{

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

{
Sindh Madressatul Islam University
Operating Systems Lab Manual

if(p[i]<=c[j])

alloc[j]=p[i];printf("\n\nAlloc[%d]",all
oc[j]);

printf("\n\nProcess %d of size %d is
allocated in block %d of size
%d",i,p[i],j,c[j]);
flag[i]=0,c[j]=0;break;
}

else
flag[i
]=1;
}

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

if(flag[i]!=0)

printf("\n\nProcess %d of size %d is not


allocated",i,p[i]);

break; case 3: printf("\nWorst


Fit\n"); for(i=0;i<nb;i++)
{

for(j=i+1;j<nb;j++)

{ if(d[i]<d[j])
{

Sindh Madressatul Islam University


Operating Systems Lab Manual

int temp=d[i];
d[i]=d[j];
d[j]=temp;
}
}

printf("\nAfter sorting block sizes:");


for(i=0;i<nb;i++) printf("\nBlock
%d:%d",i,d[i]); for(i=0;i<np;i++)
{

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

if(p[i]<=d[j])

alloc[j]=p[i];
printf("\n\nAlloc[%d]",alloc[j]);
printf("\n\nProcess %d of size %d is
allocated in block %d of size
%d",i,p[i],j,d[j]

flag[i]=0,d[j]=0;break;

else

flag[i]=1;

Sindh Madressatul Islam University


Operating Systems Lab Manual

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

if(flag[i]!=0)
printf("\n\nProcess %d of size
%d is not allocated",i,p[i]);

break; default: printf(“Invalid


Choice…!”);break; }

}while(ch<=3);

OUTPUT :

Enter the no of process:3

Enter the no of blocks:3

Enter the size of each process:

Process 0:100

Process 1:150

Process 2:200

Enter the block sizes:

Block 0:300

Block 1:350

Block 2:200

Sindh Madressatul Islam University


Operating Systems Lab Manual

1. First fit 2.Best fit 3.Worst fit

Enter your choice:1

Alloc[100]

Process 0 of size 100 is allocated in block 0 of size 300

Alloc[150]

Process 1 of size 150 is allocated in block 1 of size 350

Alloc[200]

Process 2 of size 200 is allocated in block 2 of size 200

Enter your choice:2

Best Fit

After sorting block sizes are:

Block 0:200

Block 1:300

Block 2:350
Alloc[100]

Process 0 of size 100 is allocated in block:0 of size:200

Alloc[150]

Process 1 of size 150 is allocated in block:1 of size:300

Alloc[200]

Process 2 of size 200 is allocated in block:2 of size:350 enter


your choice:3
Worst Fit

After sorting block sizes are:


Sindh Madressatul Islam University
Operating Systems Lab Manual

Block 0:350

Block 1:300

Block 2:200

Alloc[100]

Process 0 of size 100 is allocated in block 0 of size 350

Alloc[150]

Process 1 of size 150 is allocated in block 1 of size 300

Alloc[200]

Process 2 of size 200 is allocated in block 2 of size 200

Enter your choice:6

Invalid Choice…!

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 10
MEMORY MANAGEMENT TECHNIQUES

Objective: Write a C program to simulate paging technique of memory management.

PAGING:
The paging technique divides the physical memory (main memory) into fixed-size blocks that are
known as Frames and also divide the logical memory(secondary memory) into blocks of the same
size that are known as Pages.

Program:
#include<stdio.h> #include<conio.h> main()

int ms, ps, nop, np, rempages, i, j, x, y, pa, offset; int s[10], fno[10][20];
clrscr();
printf("\nEnter the memory size -- ");
scanf("%d",&ms);

printf("\nEnter the page size -- ");


scanf("%d",&ps); nop = ms/ps;

printf("\nThe no. of pages available in memory are -- %d ",nop);


printf("\nEnter number of processes -- ");
scanf("%d",&np); rempages = nop;
for(i=1;i<=np;i++)

printf("\nEnter no. of pages required for p[%d]-- ",i);


scanf("%d",&s[i]); if(s[i] >rempages)

printf("\nMemory is Full"); break;

rempages = rempages - s[i];


printf("\nEnter pagetable for p[%d] --- ",i);

Sindh Madressatul Islam University


Operating Systems Lab Manual

for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);

printf("\nEnter Logical Address to find Physical Address ");


printf("\nEnter process no. and pagenumber and offset -- ");
scanf("%d %d %d",&x,&y, &offset);

if(x>np || y>=s[i] || offset>=ps)

printf("\nInvalid Process or Page Number or offset");

else

pa=fno[x][y]*ps+offset;

printf("\nThe Physical Address is -- %d",pa);

getch();

OUTPUT
Enter the memory size – 1000

Enter the page size -- 100

The no. of pages available in memory are 10

Enter number of processes -- 3

Enter no. of pages required for p[1]-- 4

Enter pagetable for p[1] --- 8 6 9 5

Enter no. of pages required for p[2]-- 5

Enter pagetable for p[2] --- 1 4 5 7 3

Enter no. of pages required for p[3]-- 5

Memory is Full

Sindh Madressatul Islam University


Operating Systems Lab Manual

Enter Logical Address to find Physical Address Enter process no. and pagenumber and offset -
-2

60

The Physical Address is -- 760

RESULT:
Thus C program for implementing paging concept for memory management has been executed
successfully.

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 11
MEMORY MANAGEMENT TECHNIQUES
Objective: Write a C program to simulate segmentation technique of memory management.
SEGMENTATION:
Segmentation is another way of dividing the addressable memory. It is another scheme of memory
management and it generally supports the user view of memory. The Logical address space is
basically the collection of segments. Each segment has a name and a length.Basically, a process is
divided into segments. Like paging, segmentation divides or segments the memory. But there is a
difference and that is while the paging divides the memory into a fixed size and on the other hand,
segmentation divides the memory into variable segments these are then loaded into logical memory
space

Program:

#include<stdio.h>
#include<unistd.h>
void main()
{
int b[20],l[20],n,i,pa,s,a,d;
printf(“\nProgram for segmentation”);
printf(“\nEnter the number of segments:”);
scanf(“%d”,&n);
printf(“\nEnter the base address and limit register:”);
for(i=0;i<n;i++)
{
scanf(“%d”,&b[i]);
scanf(“%d”,&l[i])
}
printf(“\nEnter the logical address:”);
scanf(“%d”,&d);
for(i=0;i<n;i++)
{

Sindh Madressatul Islam University


Operating Systems Lab Manual

if(i==s)
{
if(d<l[i])
{
pa=b[i]+d;
a=b[i];
printf(“(“\n\tPageNo.\t BaseAdd. PhysicalAdd. \n\t %d \t %d \t
%d \t ”,s,a,pa);
exit(0);
}
else
{
printf(“\nPage size exceeds”);
exit(0);
}
}
}
printf(“\nInvalid segment”);
}
Sample Input 1:
Program for segmentation
Enter the number of segments:3
Enter the base address and limit register:
100 50
150 20
130 34
Enter the Logical address:25
Enter the segment number:1
Sample Output 1:
PageNo. BaseAdd. PhysicalAdd.
2 130 155
Sample Input 2:

Sindh Madressatul Islam University


Operating Systems Lab Manual

Program for segmentation


Enter the number of segments:2
Enter the Logical address and limit register:
100 50
150 20
Enter the logical address:25
Enter the segment number:1
Sample Output 2:
page size exceeds

RESULT:
Thus the program for implementing the segmentation concept was executed and the
output was verified successfully.

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 12
PAGE REPLCEMENT ALGORITHMS
Objective: Write a C program to simulate page replacement algorithms
a) FIFO b) LRU c) Optimal d)MRU
a) FIFO
The FIFO Page Replacement algorithm associates with each page the time when that page
was brought into memory. When a page must be replaced, the oldest page is chosen. There
is not strictly necessary to record the time when a page is brought in. By creating a FIFO
queue to hold all pages in memory and by replacing the page at the head of the queue.
When a page is brought into memory, insert it at the tail of the queue.

Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
clrscr();
printf("\n Enter the length of reference string -- ");
scanf("%d",&n);
printf("\n Enter the reference string -- ");
for(i=0;i<n;i++) scanf("%d",&rs[i]);
printf("\n Enter no. of frames -- ");
scanf("%d",&f); for(i=0;i<f;i++) m[i]=-1;
printf("\n The Page Replacement Process is -- \n");
for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
if(m[k]==rs[i])
break;

Sindh Madressatul Islam University


Operating Systems Lab Manual

}
if(k==f)
{
m[count++]=rs[i]; pf++;
}
for(j=0;j<f;j++)
printf("\t%d",m[j]);
if(k==f) printf("\tPF No. %d",pf);
printf("\n"); if(count==f) count=0;
}
printf("\n The number of Page Faults using FIFO are %d",pf);
getch();
}

OUTPUT :
Enter the length of reference string – 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3
The Page Replacement Process is –
7 -1 -1 PF No. 1
7 0 -1 PF No. 2
7 0 1 PF No. 3
2 0 1 PF No. 4
2 0 1
2 3 1 PF No. 5
2 3 0 PF No. 6
4 3 0 PF No. 7
4 2 0 PF No. 8
4 2 3 PF No. 9
0 2 3 PF No. 10
0 2 3
0 2 3

Sindh Madressatul Islam University


Operating Systems Lab Manual

0 1 3 PF No. 11
0 1 2 PF No. 12
0 1 2
0 1 2
7 1 2 PF No. 13
7 0 2 PF No. 14
7 0 1 PF No. 15
The number of Page Faults using FIFO are 15

RESULT:
Thus a C program using FIFO has been executed successfully.

b) LRU
The Least Recently Used replacement policy chooses to replace the page which has not been
referenced for the longest time. This policy assumes the recent past will approximate the immediate
future. The operating system keeps track of when each page was referenced by recording the time of
reference or by maintaining a stack of references.

Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i, j , k, min, rs[25], m[10], count[10], flag[25], n, f, pf=0, next=1;
clrscr();
printf("Enter the length of reference string -- ");
scanf("%d",&n);
printf("Enter the reference string -- ");
for(i=0;i<n;i++)
{
scanf("%d",&rs[i]); flag[i]=0;
}
Sindh Madressatul Islam University
Operating Systems Lab Manual

printf("Enter the number of frames -- ");


scanf("%d",&f); for(i=0;i<f;i++)
{
count[i]=0; m[i]=-1;
}
printf("\nThe Page Replacement process is -- \n");
for(i=0;i<n;i++)
{
for(j=0;j<f;j++)
{
if(m[j]==rs[i])
{
flag[i]=1; count[j]=next;
next++;
}
}
if(flag[i]==0)
{
if(i<f)
{
m[i]=rs[i]; count[i]=next;
next++;
}
else
{
min=0;
for(j=1;j<f;j++) if(count[min] > count[j])
min=j;
m[min]=rs[i]; count[min]=next;
next++;
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

pf++;
}
for(j=0;j<f;j++)
printf("%d\t", m[j]);
if(flag[i]==0)
printf("PF No. -- %d" , pf);
printf("\n");
}
printf("\nThe number of page faults using LRU are %d",pf);
getch();
}

OUTPUT
Enter the length of reference string -- 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter the number of frames -- 3
The Page Replacement process is --
7 -1 -1 PF No. -- 1
7 0 -1 PF No. -- 2
7 0 1 PF No. -- 3
2 0 1 PF No. -- 4
2 0 1
2 0 3 PF No. -- 5
2 0 3
4 0 3 PF No. -- 6
4 0 2 PF No. -- 7
4 3 2 PF No. -- 8
0 3 2 PF No. -- 9
0 3 2
0 3 2
1 3 2 PF No. -- 10
1 3 2
Sindh Madressatul Islam University
Operating Systems Lab Manual

1 0 2 PF No. -- 11
1 0 2
1 0 7 PF No. -- 12
1 0 7

1 0 7
The number of page faults using LRU are 12

RESULT:
Thus a C program to implement LRU page replacement is executed successfully.

c) OPTIMAL
The optimal Page Replacement Algorithm replaces the page which will not be referred for so long in
future. Although it can not be practically implementable but it can be used as a benchmark. Other
algorithms are compared to this in terms of optimality.

Program:
#include<stdio.h>
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k, pos,
max, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);

printf("Enter number of pages: ");


scanf("%d", &no_of_pages);

printf("Enter page reference string: ");

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


scanf("%d", &pages[i]);
}

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


frames[i] = -1;
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

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


flag1 = flag2 = 0;

for(j = 0; j < no_of_frames; ++j){


if(frames[j] == pages[i]){
flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
flag3 =0;

for(j = 0; j < no_of_frames; ++j){


temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){


if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}
}

for(j = 0; j < no_of_frames; ++j){


if(temp[j] == -1){
pos = j;
flag3 = 1;
break;
}
}

if(flag3 ==0){
max = temp[0];
pos = 0;

for(j = 1; j < no_of_frames; ++j){


Sindh Madressatul Islam University
Operating Systems Lab Manual

if(temp[j] > max){


max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults++;
}

printf("\n");

for(j = 0; j < no_of_frames; ++j){


printf("%d\t", frames[j]);
}
}

printf("\n\nTotal Page Faults = %d", faults);

return 0;
}

OUTPUT:
Enter number of frames: 3
Enter number of pages: 10
Enter page reference string: 2 3 4 2 1 3 7 5 4 3

2 -1 -1
2 3 -1
234
234
134
134
734
534
534
534

Sindh Madressatul Islam University


Operating Systems Lab Manual

d) MRU:
MRU page replacement algorithm replaces the most recently used page in the reference string.

Program:
#include <bits/stdc++.h>
using namespace std;
// Function to update the array in most recently used fashion
void recently(int* arr, int size, int elem)
{
int index = 0;
index = (elem % size);
int temp = index, id = arr[index];
while (temp > 0)
{
arr[temp] = arr[--temp];
}
arr[0] = id;
}
//print array elements
void print(int* arr, int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
int main() {
int elem = 3;
int arr[] = { 6, 1, 9, 5, 3 };
int size = sizeof(arr) / sizeof(arr[0]);
recently(arr, size, elem);
cout<<"array in most recently used fashion : ";
print(arr, size);

Sindh Madressatul Islam University


Operating Systems Lab Manual

return 0;
}

OUTPUT:

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 13
DISK SCHEDULING ALGORITHMS

Objective: Write a C program to simulate disk scheduling algorithms


a) FCFS b) SSTF c) SCAN

a) FCFS:
FCFS is the simplest disk scheduling algorithm. As the name suggests, this algorithm
entertains requests in the order they arrive in the disk queue. The algorithm looks very
fair and there is no starvation (all requests are serviced sequentially) but generally, it
does not provide the fastest service.

Program:
#include<stdio.h> main()
{
int t[20], n, I, j, tohm[20], tot=0; float avhm;
clrscr();
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”);

Sindh Madressatul Islam University


Operating Systems Lab Manual

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();
}

OUTPUT:
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160
184
Tracks traversed Difference between tracks
55 45
58 3
60 2
70 10
18 52
90 72
150 60
160 10
184 24
Average header movements:30.888889

b) SSTF:
SSTF is abbreviation of Shortest Seek Time First (SSTF) which is a disk scheduling
algorithm.It selects the request which is closest to the current head position before moving the
head away to service other requests. This is done by selecting the request which has the least
seek time from the current head position.

Program:
#include<stdio.h>
#include<stdlib.h>
int main()

Sindh Madressatul Islam University


Operating Systems Lab Manual

{
int RQ[100],i,n,TotalHeadMoment=0,initial,count=0;
printf("Enter the number of Requests\n");
scanf("%d",&n);
printf("Enter the Requests sequence\n");
for(i=0;i<n;i++)
scanf("%d",&RQ[i]);
printf("Enter initial head position\n");
scanf("%d",&initial);

// logic for sstf disk scheduling

/* loop will execute until all process is completed*/


while(count!=n)
{
int min=1000,d,index;
for(i=0;i<n;i++)
{
d=abs(RQ[i]-initial);
if(min>d)
{
min=d;
index=i;
}
}
TotalHeadMoment=TotalHeadMoment+min;
initial=RQ[index];
// 1000 is for max
// you can use any number
RQ[index]=1000;

Sindh Madressatul Islam University


Operating Systems Lab Manual

count++;
}
printf("Total head movement is %d",TotalHeadMoment);
return 0;

OUTPUT:

c) SCAN:
It is also called as Elevator Algorithm. In this algorithm, the disk arm moves into a
particular direction till the end, satisfying all the requests coming in its path, and
then it turns backend moves in the reverse direction satisfying requests coming in
its path. It works in the way an elevator works, elevator moves in a direction
completely till the last floor of that direction and then turns back.\

Program:
#include<stdio.h>
main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;

Sindh Madressatul Islam University


Operating Systems Lab Manual

clrscr();
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);

Sindh Madressatul Islam University


Operating Systems Lab Manual

getch();
}

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

Sindh Madressatul Islam University


Operating Systems Lab Manual

LAB No: 14

FILE ALLOCATION STRATEGIES

Objective: Write a C program to simulate the following file allocation strategies.


a) Sequential b) Indexed c) Linked

a) SEQUENTIAL:
In this allocation strategy, each file occupies a set of contiguously blocks on the disk. This strategy
is best suited. For sequential files, the file allocation table consists of a single entry for each file. It
shows the filenames, starting block of the file and size of the file. The main problem with this
strategy is, it is difficult to find the contiguous free blocks in the disk and some free blocks could
happen between two files.

Program:
#include<stdio.h>
main()
{ int f[50],i,st,j,len,c,k;
clrscr(); 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");

Sindh Madressatul Islam University


Operating Systems Lab Manual

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();
getch();
}

OUTPUT:
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
If you want to enter more files? (Y-1/N-0)

RESULT :
Thus the program to implement the Sequential file allocation was
executed successfully.

Sindh Madressatul Islam University


Operating Systems Lab Manual

b) INDEXED:
In this scheme, a special block known as the Index block contains the pointers to all the blocks
occupied by a file. Each file has its own index block. The ith entry in the index block contains
the disk address of the ith file block. The directory entry contains the address of the index.

Program:
#include<stdio.h>
int f[50],i,k,j,inde[50],n,c,count=0,p; main()
{ clrscr(); for(i=0;i<50;i++) f[i]=0;
x: printf("enter index block\t"); scanf("%d",&p); if(f[p]==0)
{
f[p]=1;
printf("enter no of files on index\t"); s canf("%d",&n);
}
else
{
printf("Block already allocated\n"); goto x;
}
for(i=0;i<n;i++) scanf("%d",&inde[i]);
for(i=0;i<n;i++) if(f[inde[i]]==1)
{
printf("Block already allocated"); goto x;
}
for(j=0;j<n;j++) f[inde[j]]=1;
printf("\n allocated"); printf("\n file indexed"); for(k=0;k<n;k++) printf("\n %d-
>%d:%d",p,inde[k],f[inde[k]]);
printf(" Enter 1 to enter more files and 0 to exit\t"); s scanf("%d",&c); if(c==1) goto x;
else exit();
getch();
}

Sindh Madressatul Islam University


Operating Systems Lab Manual

OUTPUT:
Enter index block 9
Enter no of files on index 3 1 2 3
Allocated
File indexed 9-> 1:1
9-> 2:1
9->3:1
Enter 1 to enter more files and 0 to exit.
RESULT :
Thus the program to implement the indexed file allocation was executed successfully.

c) LINKED:
In this scheme, each file is a linked list of disk blocks which need not be contiguous. The disk
blocks can be scattered anywhere on the disk.The directory entry contains a pointer to the
starting and the ending file block. Each block contains a pointer to the next block occupied by
the file.

Program:
#include<stdio.h>
main()
{
int f[50],p,i,j,k,a,st,len,n,c; clrscr();
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");

Sindh Madressatul Islam University


Operating Systems Lab Manual

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();
getch( );
}
OUTPUT:
Enter how many blocks are already allocated 3
Enter the blocks no’s that are already allocated 4 7 9
Enter the starting index block & length 3 7
3-> 1
4-> File is already allocated 5->1
6->1
7-> File is already allocated 8->1
9-> File is already allocated 10->1
11->1
12->1
If u want to enter one more file? (yes-1/no-0)
RESULT:
Thus the program to implement the linked file allocation was executed successfully

Sindh Madressatul Islam University

You might also like