Operating System Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Lab 1

AIM: To study basic commands in LINUX OS

COMMAND: Linux command is a utility of Linux operating system. All basic and advanced tasks can be done by executing
commands. The commands can be broadly categorized as follows:

1) Linux Directory commands:

i. pwd: Used to display location of current working directory. (Syntax: pwd)


ii. mkdir: Used to create a new directory under any directory. (Syntax: mkdir <directory_name>)
iii. rmdir: Used to delete a directory (Syntax: rmdir <directory-name>)
iv. ls: Used to display list of content of directory. (Syntax: ls)
v. cd: used to change the current directory. (Syntax: cd <directory_name>)

2) LINUX File Commands

i. touch: Used to create empty files. (Syntax: touch <file+name>, touch <file 1><file 2>…)
ii. cat. Used to create a file, display content of file, copy content of one file to another and more.
(Syntax: cat [OPTION]...[FILE]..)
iii. rm: Used to remove a file. (Syntax: rm <file_name>)
iv. ср: Used to сору a file. (Syntax: cp <existing file_name> <new file_name>)
v. mv: Used to move a file or directory from one location to another. (Syntax: mv <file_name> <directory_path>)

3) LINUX File Content commands

i. head: Used to display content of file. It displays the first 10 lines of file. (Syntax: head <file_name>)
ii. tail: Similar to head command. It displays last 10 line of file. (Syntax: tail <file_name>)
iii. tac: Reverse of cat command. It displays file content in reverse order. (Syntax: tac<file>)
iv. more: Used to display screenful output at a time. (Syntax: more <file_name>)
v. less: Similar to more command with additional features such as 'adjustment in width and height of the terminal (Syntax: less
<file_name>)

4) Linux User Commands

i. su: Provides administrative access to another user. (Syntax: su <user name>)


ii. id: Used to display user ID and group id. (Syntax: id)
iii. useradd: Used to add or remove a user on Linux server. (Syntax: useradd username)
iv. passwd: Used to create and change password for a user. (Syntax: passwd <username>)
v. groupadd: Used to create a user group. (Syntax: groupadd <group_name>)

5) Linux Filter Commands

i. cut: Used to select specific column of file. (Syntax: cut-d(delimiter) - f(ColumnNumber) <file_name>)
ii. grep: Used to search content from a file. (Syntax: command|grep <SearchWord>)
iii. comm: Used to compare two files or streams. (Syntax: comm <file1> <file2>)
iv. tr: Used to translate file content like from lower case to upper case. (Syntax: command|tr< 'old'> <new'>)
v. wc: Used to count the lines, words, and characters in file. (Syntax: wc <file_name>)

6) Linux Utility commands

i. date: Used to display date, time, time zone... (Syntax: date)


ii. cal: Used to display current month's calendar with current date highlighted. (Syntax: cal<<month>year>)
iii. time: Used to display time to execute a command. (Syntax: time)
iv. db: Used to display disk space used in file system. (Syntax: df)
v. exit: Used to exit from current shell. (Syntax: exit)
vi. clear: Used to clear the terminal screen. (Syntax: clear)
Lab 2
AIM: To write a C program to implement thread and process

THEORY: A thread is a lightweight process that runs with other threads concurrently within a process. Each thread has its own stack
and register sets. However, they share common code, data and file services. They are often implemented to improve the performance
of applications by allowing multiple tasks to be executed concurrently.

A process, is a dynamic instance of program under execution. It is an independent entity. Each process has its own memory and set of
OS resources like files and CPU time. Each process is isolated from the other providing security and stability.

SOURCE CODE:

#include<stdio.h>

#include<stdlib.h>

#include <unistd.h>

#include<pthread.h>

void *myThreadFun (void *vary) {

sleep (1)

print("Printing Hello world! from Thread \n");

return NULL;}

int main(){

pthred_t thread_id;

printf("Before thread ");

pthread_create(&thread_id, NLL, myThreadFun, NULL);

pthread_join (thread_id, NULL);

printf(After thread \n ");

exit (0);}

SAMPLE OUTPUT:

Before thread

Printing Hello world! from Thread

After thread
Lab 3
AIM: To write a C program to implement producer-consumer problem using semaphores

THEORY: Producer consumer problem is a synchronization problem. There is a fixed size buffer where producer produces item and
consumer consumes it. One solution uses the shared memory. To allow both to run concurrently, there must be buffer of items
available that can be filled by producer and emptied by the consumer.

SOURCE CODE:

#include <stdio.h>

#include <stdlib.h>

int mutex = 1;

int full =0;

int empty=10, x=0;

void producer(){

--mutex;

++full;

--empty;

x++;

printf("\n Producer produces item "%d",x);

++mutex;}

void consumer(){

--mutex;

--full;

++empty;

printf(“\n Consumer consumes item %d",x);

x--;

++mutex;}

int main(){

int n,i;

printf(“1.Press 1 for Producer \n 2.Press 2 for Consumer \n 3.Press 3 for Exit");

for (i=1;i>0; i++){

printf("\n Enter your choice:”);

scanf("%d", &n);

switch(n){

case 1:

if ((mutex == 1) && (empty!=0)) producer();

else

printf("Buffer is full");
break;

case 2:

if((mutex==1) && (full != 0)) consumer();

else

printf("Buffer is empty");

break;

case 3:

exit (0);

printf("Exiting!");

break;}}}

SAMPLE OUTPUT:

1. Press 1 for Producer

2. Press 2 for consumer

3. Press 3 for exit

Enter your choice: 1

Producer produces item 1

Enter your choice: 1

Producer produces item 2

Enter your choice: 2

Consumer consumes item 2

Enter your choice: 2

Consumer consumes item 1

Enter your choice: 2

Buffer is empty

Enter your choice: 3

Exiting!
Lab 4
AIM: To write a C program to simulate Dining-philosopher problem

THEORY: Dining-philosophers problem is a classic synchronization and concurrency problem that illustrates the challenges of
resource allocation and deadlock avoidance. In this scenario, five philosophers sit round a circular table, each thinking and eating.
Between, each pair of philosopher, there is a single fork. The goal is to ensure that each philosopher can pick up both forks (left and
right) to eat without causing a dead lock.

SOURCE CODE:

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <semaphore.h>

#define N5

sem_t forks [N];

pthread_t philosophers [N];

void *philosopher (void * arg){

int philID= *(int*)arg;

int leftFork: philID;

int rightFork (philID + 1) % N;

printf("Philosopher %d is thinking....\n", philID);

sem_wait(&forks [leftFork]);

printf("Philosopher %d picked up fork %d(left)\n", philID, leftFork);

printf("Philosopher %d picked up fork %d(right)\n", philID, rightFork);

sem_wait (&forks[rightFork]);

printf(“Philosopher %d is eating\n”philID);

sem_post(&forks[leftFork]);

sem-post(&forks[rightFork]);

printf(“Philosopher %d finished eating\n”philID);

pthread_exit(NULL);}

int main(){

int i;

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

sem_init(&forks[i],0,1);

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

int *philID=(int*)malloc(sizeof(int));

philID=i;

pthread_create(&philosopher[i],NULL,philosopher,philID);}
for(i=0;i<N;i++)

pthread_join(philosophers[i],NULL);

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

sem_destroy(&forks[i]);}

return 0;}

SAMPLE OUTPUT:

Philosopher 0 is thinking…

Philosopher 0 picked up fork 0(left)

Philosopher 0 picked up fork 1(right)

Philosopher 0 is eating

Philosopher 0 finished eating

Philosopher 4 is thinking…

Philosopher 4 picked up fork 4(left)

Philosopher 4 picked up fork 0(right)

Philosopher 4 is eating

Philosopher 4 finished eating

Philosopher 3 is thinking…

Philosopher 3 picked up fork 3(left)

Philosopher 4 picked up fork 4(right)

Philosopher 3 is eating

Philosopher 3 finished eating

Philosopher 1 is thinking…

Philosopher 1 picked up fork 1(left)

Philosopher 1 picked up fork 2(right)

Philosopher 1 is eating

Philosopher 1 finished eating

Philosopher 2 is thinking…

Philosopher 2 picked up fork 2(left)

Philosopher 2 picked up fork 3(right)

Philosopher 2 is eating

Philosopher 2 finished eating


Lab 5
a) FCFS

AIM: To simulate the CPU scheduling algorithm First Come First serve (FCFS)

ALGORITHM:

Step 1: Start the process

Step 2. Accept the number of processes in ready queue.

Step 3: For each process in the ready Q, assign the process name and the burst time

Step 4: Set the waiting time of the first process as 0 and its burst time as its turnaround time

Step 5: For each process in ready queue calculate,

a) waiting time(n): waiting time (n-1) + Burst time(n-1)

b) turnaround time(n) = waiting time (n)+ Burst time(n)

Step 6: Calculate

a) Average waiting time: Total waiting time/No. of process

b) Average turnaround time: Total turnaround time/No. of process

Step 7: Stop

SOURCE CODE:

#include<stdio.h>

#include<conio.h>

main() {

int bt[20], wt[20], tat[20], i, n;

float wtavg, tatavg;

clrscr();

printf("\n Enter the number of processes-- ");

scanf("%d", &n);

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

printf("\n Enter 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++) {

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 \t BURST 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("\n Average Waiting Time--%f", wtavg/n);

printf("\n Average Turnaround Time -- %f", tatavg/n);

getch(); }

SAMPLE OUTPUT:

Enter the number of processes -- 3

Enter Burst Time for Process 0-- 24

Enter Burst Time for Process 1 -- 3

Enter Burst Time for Process 2 -- 3

PROCESS BURST TIME WAITING TIME TURNAROUNDTIME

P0 24 0 24

P1 3 24 27

P2 3 27 30

Average Waiting Time--17.000000

Average Turnaround Time--27.000000

b) SJF

AIM: To simulate CPU scheduling algorithm Shortest Job First (SJF)

ALGORITHM:

Step 1: Start the process.

Step 2: Accept the number of processes in ready queue

Step 3: For each process in ready Q, assign the process id and accept the cpu burst time

Step 4: Start the ready & according to the shortest burst time by sorting according to lowest to highest burst time.

Step 5: Set the waiting time for first process as 0 and its turnaround time as burst time.

Step 6: For each process in ready Q, compute

a) waiting time(n)= waiting time (n-1) + Burst time(n-1)

b) turnaround time (n) = waiting time(n)+ Burst time (n)

Step 7: Calculate:

a) Average waiting time: Total waiting time / No. of processes

b) Average turnaround time: Total turnaround time/ No. of processes

Step 8: Stop the process.

SOURCE CODE:

#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;}

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;

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

wt[i]=0;

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

wt[i]+=bt[j];

total+=wt[i]; }

avg_wt=(float)total/n;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");

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

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

totalT+=tat[i];

printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);}

avg_tat=(float)totalT/n;

printf("\n\nAverage Waiting Time=%f",avg_wt);

printf("\nAverage Turnaround Time=%f",avg_tat);}


c) CPU Priority scheduling

AIM: To simulate the CPU scheduling priority algorithm

ALGORITHM:

Step 1: Start the process.

Stop 2: Accept the number of process in ready queue. Step3: For each process in ready Q, assign the process id and accept CPU burst
time

stopy: Sort the ready queue according to priority step 5. set waiting of first process as o and its burst

time as its turnaround time

Step 6: Arrange the process based on process priority Step 7. For each process in ready a, calculate

a) waiting time (n) = waiting time (n-1)+ burst time (nm) b) turnaround time (n) = burst time (n) + waiting time(n) Step 9: Calculate

a) Average WT: Total WT/NO. of process 6) Average TAT = Total TAT/NO. of process

Stop 10: stop.

SOURCE CODE:

#include <stdio.h>

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

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;

for(int j=i;j<n;j++){

if(p[j] > a){

a=p[j];

m=j;}}

swap(&p[i], &p[m]);

swap(&b[i], &b[m]);

swap(&index[i],&index[m]);}
int t=0;

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

Lab 6
AIM: To simulate preemptive CPU scheduling algorithm in C

a) Round robin

#include<stdio.h>

#include<conio.h>

int main() {

int i, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];

float avg_wt, avg_tat;

printf(" Total number of process in the system: ");

scanf("%d", &NOP);

y = NOP;

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

printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);

printf(" Arrival time is: \t"); // Accept arrival time

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

printf(" \nBurst time is: \t");

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

temp[i] = bt[i]; }

printf("Enter the Time Quantum for the process: \t");

scanf("%d", &quant);

printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");

for(sum=0, i = 0; y!=0; ) {
if(temp[i] <= quant && temp[i] > 0) // define the conditions {

sum = sum + temp[i];

temp[i] = 0;

count=1; }

else if(temp[i] > 0) {

temp[i] = temp[i] - quant;

sum = sum + quant; }

if(temp[i]==0 && count==1) {

y--;

printf("\nProcess No[%d] \t\t %d\t\t\t\t %d\t\t\t %d", i+1, bt[i], sum-at[i], sum-at[i]-bt[i]);

wt = wt+sum-at[i]-bt[i];

tat = tat+sum-at[i];

count =0; }

if(i==NOP-1)

{i=0;}

else if(at[i+1]<=sum)

{ i++; }

else {

i=0; }}

avg_wt = wt * 1.0/NOP;

avg_tat = tat * 1.0/NOP;

printf("\n Average Turn Around Time: \t%f", avg_wt);

printf("\n Average Waiting Time: \t%f", avg_tat);

return 0; }

b) Priority

#include<stdio.h>

struct process{

int WT,AT,BT,TAT,PT;};

struct process a[10];

int main(){

int n,temp[10],t,count=0,short_p;

float total_WT=0,total_TAT=0,Avg_WT,Avg_TAT;

printf("Enter the number of the process\n");

scanf("%d",&n);

printf("Enter the arrival time , burst time and priority of the process\n");
printf("AT BT PT\n");

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

scanf("%d%d%d",&a[i].AT,&a[i].BT,&a[i].PT);

temp[i]=a[i].BT;}

a[9].PT=10000;

for(t=0;count!=n;t++){

short_p=9;

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

if(a[short_p].PT>a[i].PT && a[i].AT<=t && a[i].BT>0){

short_p=i;}}

a[short_p].BT=a[short_p].BT-1;

if(a[short_p].BT==0) {

count++;

a[short_p].WT=t+1-a[short_p].AT-temp[short_p];

a[short_p].TAT=t+1-a[short_p].AT;

total_WT=total_WT+a[short_p].WT;

total_TAT=total_TAT+a[short_p].TAT;}}

Avg_WT=total_WT/n;

Avg_TAT=total_TAT/n;

printf("ID WT TAT\n");

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

printf("%d %d\t%d\n",i+1,a[i].WT,a[i].TAT);}

printf("Avg waiting time of the process is %f\n",Avg_WT);

printf("Avg turn around time of the process is %f\n",Avg_TAT);

return 0;}
Lab 7
AIM: To simulate Banking algorithm for deadlock avoidance

SOURCE CODE:

#include <stdio.h>

#include <conio.h>

void main() {

int k=0,a=0,b=0,instance[5],availability[5],allocated[10][5],need[10][5],MAX[10][5],process,P[10],no_of_resources, cnt=0,i, j;

printf("\n Enter the number of resources : ");

scanf("%d", &no_of_resources);

printf("\n enter the max instances of each resources\n");

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

availability[i]=0;

printf("%c= ",(i+97));

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

printf("\n Enter the number of processes : ");

scanf("%d", &process);

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

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

printf(" %c",(i+97));

printf("\n");

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

P[i]=i;

printf("P[%d] ",P[i]);

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

scanf("%d",&allocated[i][j]);

availability[j]+=allocated[i][j];}}

printf("\nEnter the MAX matrix \n ");

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

printf(" %c",(i+97));

availability[i]=instance[i]-availability[i];}

printf("\n");

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

printf("P[%d] ",i);

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

scanf("%d", &MAX[i][j]);}
printf("\n");

A: a=-1;

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

cnt=0;

b=P[i];

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

need[b][j] = MAX[b][j]-allocated[b][j];

if(need[b][j]<=availability[j])

cnt++;}

if(cnt==no_of_resources) {

op[k++]=P[i];

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

availability[j]+=allocated[b][j];

} else

P[++a]=P[i];}

if(a!=-1) {

process=a+1;

goto A;}

printf("\t <");

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

printf(" P[%d] ",op[i]);

printf(">");

return 0();}
Lab 9
AIM: To simulate MVT and MFT memory management techniques

THEORY: MVT (Multi-programming with a variable number of tasks) is the memory management technique in which each job gets
the right amount of memory it needs. That is, partitioning of memory is dynamic and changes as jobs enter and leave the system. MVT
is a more efficient user of resources. MFT (Multi-programming with a Fixed number of Tasks) is one of the oldest memory
management techniques in which the memory is partitioned into fixed sized partitions and each job is assigned into a partition. The
memory assigned to a partition does not change. MFT suffers from internal fragmentation while MVT suffters from external
fragmentation.

SOURCE CODE:

#include <stdio.h> // MVT memory management technique

int main(){

ind ms, mp[10], i, temp, n=0;

char ch=’y’;

printf(“Enter the total memory available (in Bytes):");

scanf("%d", &ms);

temp=ms;

for (i=0; ch=='y';i++;n++){

printf(“Enter memory required for process %d (in Bytes):”,i+1);

scanf(“%d”&mp[i]);

if (mp[i]<=temp){

printf(“Memory allocated for process %d”,i+1);

temp=temp-mp[i];}

else{

printf(“Memory full”);

break;}

printf(“Do you want to continue (y/n):”);

scanf(“%c”,&ch);}

printf(“Total memory available:%d”,ms);

printf(“\n\tProcess\tMemory allocated”);

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

printf(“\n\t%d\t%d”,i+1,mp[i]);

printf(“\nTotal Memory allocated is %d”,ms-temp);

printf(“\nTotal external fragmentation is %d”,temp);

return 0;}

SAMPLE OUTPUT:

Enter the total memory available (in Bytes): 10000

Enter the memory required for process (in Bytes): 400


Memory allocated for process 1

Do you want to continue (y/n): y

Enter memory required for process 2 (in Bytes): 275

Memory allocated for process 2

Do you want to continue (y/n): y

Enter memory required for process: 3 (in bytes): 550

Memory full

Total Memory Available: 1000

Process Memory Allocated

1 400

2 275

Total Memory Allocated is 675

Total External Fragmentation is 325

//MFT memory management techniques

#include <stdio.h>

int main(){

int ms,bs,nob,ef,n,mp[10],fif = 0;

int i,p: 0;

printf""Enter the total memory available (in Bytes):");

scanf(“%d", &ms);

printf("Enter the block size (in Bytes) : ");

scanf("%d", &bs);

nob= ms/bs;

ef= ms-nob*bs;

printf("\n Enter the number of processes: ");

scanf(“%d", &n);

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

printf("Enter memory required for process %d (in Bytes):”, i+1);

scanf("%d", &mpli]);}

printf("No. of Blocks available in memory %d", nob);

printf("\nProcess\tMemory Required\tAllocated\tInternal Fragmentation");

for(i=0; i<n&& p<nob; i++){

printf("\n%d\t%d",i+1, mp[i]);

if (mp[i]>bs)
print("\t NO\t");

else{

printf("\tYes \t %d", bs-mp[i]);

tif=tif+bs-mp[i];

p++;}}

if (i<n)

printf(“Memory is full, Remaining Processes cannot be accomodated");

printf(“Total Internal Fragmentation is %d”,tif);

printf(“Total External Fragmentation is %d”,ef);

return 0;}

SAMPLE OUTPUT:

Enter the total memory available (in Bytes): 1000

Enter the block size (in Bytes): 300

Enter the number of processes: 5

Enter memory required for process 1 (in Bytes): 275

Enter memory required for process 1 (in Bytes): 275

Enter memory required for process 1 (in Bytes): 275

Enter memory required for process 1 (in Bytes): 275

Enter memory required for process 1 (in Bytes): 275

No. of blocks available in memory: 3

Process Memory Required Allocated Internal Fragmentation

1 275 Yes 25

2 400 NO --

3 290 Yes 10

4 293 Yes 7

Memory is full, Remaining Processes cannot be accommodated

Total Internal Fragmentation is 42

Total External Fragmentation is 100


Lab 10
AIM: To simulate paging technique of memory management

THEORY: Paging is a memory management scheme wherein the CPU stores and retrieves data from secondary storage for use in
primary memory at time of execution. The OS retrieves data from secondary memory in same size blocks known as pages. Page is a
memory block of same size. Paging technique plays an important role in virtual memory which is portion of disk reserved to emulate
computer's RAM. Size of process is measured in terms of number of pages.

SOURCE CODE:

#include<stdio.h>

#include<conio.h>

int main(){

int ms, ps, nop, np, rempages, i, j, x, y, pa, offset;

int s[10], fno[10][20];

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

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

return 0;}

SAMPLE 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

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

The Physical Address is -- 760


Lab 11
AIM: To simulate FIRST-FIT contiguous memory allocation technique in C

THEORY: One of the simplest methods for memory allocation is to divide memory into equal sized partitions. Each partition may
contain exactly one process. First fit is simplest algorithm. In this case, it allocates the first available partition that is large enough to
accommodate the process. It searches for suitable partition from the beginning.

SOURCE CODE:

#include<stdio.h>

void firstFit(int blockSize[], int m, int processSize[], int n){

int i, j;

int allocation[n];

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

allocation[i] = -1; }

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

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

if (blockSize[j] >= processSize[i]) {

allocation[i] = j;

blockSize[j] -= processSize[i];

break; } } }

printf("\nProcess No.\tProcess Size\tBlock no.\n");

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

printf(" %i\t\t\t", i+1);

printf("%i\t\t\t\t", processSize[i]);

if (allocation[i] != -1)

printf("%i", allocation[i] + 1);

else

printf("Not Allocated");

printf("\n"); } }

int main() {

int m;

int n;

int blockSize[] = {100, 500, 200, 300, 600};

int processSize[] = {212, 417, 112, 426};

m = sizeof(blockSize) / sizeof(blockSize[0]);

n = sizeof(processSize) / sizeof(processSize[0]);

firstFit(blockSize, m, processSize, n);

return 0 ;}
Lab 12
AIM: To simulate BEST-FIT contiguous memory allocation technique in C

THEORY: Best-fit is another memory allocation technique. It allocates the smallest available partition that is large enough to
accommodate the process. It requires searching the entire list of partition to bind the best match.

SOURCE CODE:
#include <stdio.h>

void implimentBestFit(int blockSize[], int blocks, int processSize[], int proccesses){

int allocation[proccesses];

int occupied[blocks];

for(int i = 0; i < proccesses; i++){

allocation[i] = -1;}

for(int i = 0; i < blocks; i++){

occupied[i] = 0;}

for (int i = 0; i < proccesses; i++){

int indexPlaced = -1;

for (int j = 0; j < blocks; j++) {

if (blockSize[j] >= processSize[i] && !occupied[j])

if (indexPlaced == -1)

indexPlaced = j;

else if (blockSize[j] < blockSize[indexPlaced])

indexPlaced = j;} }

if (indexPlaced != -1){

allocation[i] = indexPlaced;

occupied[indexPlaced] = 1;} }

printf("\nProcess No.\tProcess Size\tBlock no.\n");

for (int i = 0; i < proccesses; i++){

printf("%d \t\t\t %d \t\t\t", i+1, processSize[i]);

if (allocation[i] != -1)

printf("%d\n",allocation[i] + 1);

else

printf("Not Allocated\n");}}

int main(){

int blockSize[] = {100, 50, 30, 120, 35};

int processSize[] = {40, 10, 30, 60};

int blocks = sizeof(blockSize)/sizeof(blockSize[0]);


int proccesses = sizeof(processSize)/sizeof(processSize[0]);

implimentBestFit(blockSize, blocks, processSize, proccesses);

return 0 ;}

SAMPLE OUTPUT:

Process No. Process Size Block no.

1 10 2

2 30 1

3 60 4

4 30 4

Lab 13
AIM: To simulate WORST-FIT contiguous memory allocation technique in C

THEORY: Worst-fit is another contiguous memory allocation technique used in fixed sized partition. It allocates the largest available
partition. It requires searching the entire list of partitions to fi the largest available space.

SOURCE CODE:

#include <stdio.h>

void implimentWorstFit(int blockSize[], int blocks, int processSize[], int processes){

int allocation[processes];

int occupied[blocks];

for(int i = 0; i < processes; i++){

allocation[i] = -1;}

for(int i = 0; i < blocks; i++){

occupied[i] = 0;}

for (int i=0; i < processes; i++){

int indexPlaced = -1;

for(int j = 0; j < blocks; j++){

if(blockSize[j] >= processSize[i] && !occupied[j]){

if (indexPlaced == -1)

indexPlaced = j;

else if (blockSize[indexPlaced] < blockSize[j])

indexPlaced = j;}}

if (indexPlaced != -1)

allocation[i] = indexPlaced;
occupied[indexPlaced] = 1;

blockSize[indexPlaced] -= processSize[i];}}

printf("\nProcess No.\tProcess Size\tBlock no.\n");

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

printf("%d \t\t\t %d \t\t\t", i+1, processSize[i]);

if (allocation[i] != -1)

printf("%d\n",allocation[i] + 1);

else

printf("Not Allocated\n");}}

int main()

int blockSize[] = {100, 50, 30, 120, 35};

int processSize[] = {40, 10, 30, 60};

int blocks = sizeof(blockSize)/sizeof(blockSize[0]);

int processes = sizeof(processSize)/sizeof(processSize[0]);

implimentWorstFit(blockSize, blocks, processSize, processes);

return 0;

SAMPLE OUTPUT:
Process No. Process Size Block no.

1 40 4

2 10 1

3 30 2

4 60 Not Allocated
Lab 14
AIM: To simulate FIFO page replacement algorithm in C

THEORY: FIFO is the simplest page replacement algorithm. In this algorithm, the OS keeps tracks of all pages in memory in queue,
the oldest page is in the front of queue. When a page needs to be replaced page in the front of queue is selected for removal.

ALGORITHM:

Step 1: Start the process.

Step 2: Declare the size with respect to page length

Step 3: Check the need of replacement from the page to memory.

Step 4: Check the need of replacement from old to new page in memory.

Step 5: Form a queue to hold all pages.

Step 6: Insert page required memory into queue.

Step 7: Check for bad replacement and page fault.

Step 8: Get the number of processes to be inserted.

Step 9 Display the values.

Step 10: Stop the process.

SOURCE CODE:

#include < stdio.h >

int main() {

int incomingStream[] = {4 , 1 , 2 , 4 , 5};

int pageFaults = 0;

int frames = 3;

int m, n, s, pages;

pages = sizeof(incomingStream)/sizeof(incomingStream[0]);

printf(" Incoming \ t Frame 1 \ t Frame 2 \ t Frame 3 ");

int temp[ frames ];

for(m = 0; m < frames; m++){

temp[m] = -1; }

for(m = 0; m < pages; m++){

s = 0;

for(n = 0; n < frames; n++) {

if(incomingStream[m] == temp[n]) {

s++;

pageFaults--; }}

pageFaults++;

if((pageFaults <= frames) && (s == 0)) {


temp[m] = incomingStream[m]; }

else if(s == 0) {

temp[(pageFaults - 1) % frames] = incomingStream[m]; }

printf("\n");

printf("%d\t\t\t",incomingStream[m]);

for(n = 0; n < frames; n++){

if(temp[n] != -1)

printf(" %d\t\t\t", temp[n]);

else

printf(" - \t\t\t"); }}

printf("\nTotal Page Faults:\t%d\n", pageFaults);

return 0; }

SAMPLE OUTPUT:

Incoming Frame 1 Frame 2 Frame 3

4 4 - -

1 4 1 -

2 4 1 2

4 4 1 2

5 5 1 2

Total Page Faults: 4

Lab 15
AIM: To simulate LRU page replacement algorithm in C

THEORY: LRU is a technique used in operating system to manage memory and improve system performance. LRU algorithm keeps
track of the pages that have been accessed recently and discards the ones that have not been used for the longest time.

ALGORITHM:

Step1: start the process

Step 2: Declare the size

Step 3: Get the number of pages to be inserted

Step 4: Get the value

Step 5: Define counter and stack

Step 6: Select the least recently used page by counter value

Step 7: stack them according to selection.

Step 8: Display the values.

Step 9: Stop

SOURCE CODE:
#include<stdio.h>

int main(){

int m, n, position, k, l;

int a = 0, b = 0, page_fault = 0;

int total_frames = 3;

int frames[total_frames];

int temp[total_frames];

int pages[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3, 6, 1, 2, 4, 3};

int total_pages = sizeof(pages)/sizeof(pages[0]);

for(m = 0; m < total_frames; m++){

frames[m] = -1;}

for(n = 0; n < total_pages; n++){

printf("%d: ", pages[n]);

a = 0, b = 0;

for(m = 0; m < total_frames; m++){

if(frames[m] == pages[n]){

a = 1;

b = 1;

break;}}

if(a == 0){

for(m = 0; m < total_frames; m++){

if(frames[m] == -1){

frames[m] = pages[n];

b = 1;

page_fault++;

break;}}}

if(b == 0){

for(m = 0; m < total_frames; m++){

temp[m] = 0;}

for(k = n - 1, l = 1; l <= total_frames - 1; l++, k--){

for(m = 0; m < total_frames; m++){

if(frames[m] == pages[k]){

temp[m] = 1;}}}

for(m = 0; m < total_frames; m++){

if(temp[m] == 0)
position = m;}

frames[position] = pages[n];

page_fault++;}

for(m = 0; m < total_frames; m++){

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

printf("\n");}

printf("\nTotal Number of Page Faults:\t%d\n", page_fault);

return 0;}

Lab 16
AIM: To simulate LFU page replacement algorithm in C

THEORY: LFU algorithm keeps track of how frequently each page is accessed and replaces the page that has been accessed the least
number of times. This is based on the principle of locality of reference, which states that recently used pages are more liked to be used
again in the near future.

ALGORITHM:

Step 1: Start

Step 2: Read number of pages and frames

Step 3: Read each page value

Step 4: Search for page in frames

Step 5: If not available allocate free frame

Step 6: If no frames is free, replace the page that is used the least

Step 7: Print number of page faults

Step 8: Stop.

SOURCE CODE:

#include<stdio.h>

int main(){

int rs[50], i, j, k, m, f, cntr[20], a[20], min, pf=0;

printf("\nEnter number of page references -- ");

scanf("%d",&m);

printf("\nEnter the reference string -- ");

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

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

printf("\nEnter the available no. of frames -- ");

scanf("%d",&f);

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

cntr[i]=0; a[i]=-1;}
printf(“\nThe Page Replacement Process is – \n“);

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

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

if(rs[i]==a[j]){

cntr[j]++;

break;

if(j==f)

{ min = 0;

for(k=1;k<f;k++)

if(cntr[k]<cntr[min])

min=k;

a[min]=rs[i]; cntr[min]=1;

pf++;}

printf("\n");

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

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

if(j==f)}

printf(“\tPF No. %d”,pf);}

printf(" Total number of page faults -- %d",pf);

return 0;}

SAMPLE OUTPUT:

Enter number of page references -- 10

Enter the reference string -- 1 2 3 4 5 2 5 2 5 1 4 3

Enter the available no. of frames – 3

The Page Replacement Process is –

1 -1 -1 PF No. 1

1 2 -1 PF No. 2

1 2 3 PF No. 3

4 2 3 PF No. 4

5 2 3 PF No. 5

523

523

5 2 1 PF No. 6

5 2 4 PF No. 7

5 2 3 PF No. 8 Total number of page faults – 8


Lab 17
AIM: To simulate optimal page replacement algorithm in C

THEORY: Optimal page replacement is a memory management technique that replaces the page which will not be used for the
longest period of time in the future. It is the most efficient page replacement algorithm, but also the most difficult to implement. It
works by keeping track of the future references to each page in memory. When a page needs to be replaced, the algorithm selects page
that will not be referenced again for the longest period of time.

ALGORITHM:

Step 1: Start

Step 2: Read number of pages

Step 3: Read each page value and frames

Step 4: search for page in frames

Step 5: If not available, allocate tree frame

Step 6: If no free frame, replace the page that is lastly used

Step 7: Print page number of page faults

Step 8: Stop.

SOURCE CODE:
#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;}

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){

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

SAMPLE 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

Total page faults = 6


Lab 18
AIM: To simulate the following file organization technique a)Single level directory b)Two level directory c) Hierarchical THEORY:
THEORY: Directory structure is the organization of files into a hierarchy of folders. In a single directory system, all the files are
placed in one directory. There is a root directory which has all the files. The advantage of single level directory system is that it is easy
to find a file within the directory. In two level directory, each user has one user file directory(UFD) The system maintains a master
block that has one entry for each user. This master block contains the address of directory of users when user logs in, system's master
file directory (MFD) is searched When user refers to particular file, only his own UFD is searched. This solves the name collision
problem and isolates user from one another. Hierarchical directory structure allows users to create their own subdirectories and to
organize their files according. A tree is the most common directory structure. The tree has a root directory and every file in the system
a unique path name. A directory contains a set of files or other subdirectories.

a) Single level directory

#include<stdio.h>

#include<conio.h>

#include<string.h>

int main(){

int nf=0,i=0,j=0,ch;

char mdname[10],fname[10][10],name[10];

printf("Enter the directory name:");

scanf("%s",mdname);

printf("Enter the number of files:");

scanf("%d",&nf);

do{

printf("Enter file name to be created:");

scanf("%s",name);

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

if(!strcmp(name,fname[i]))

break;}

if(i==nf){

strcpy(fname[j++],name);

nf++;}

else

printf("There is already %s\n",name);

printf("Do you want to enter another file(yes - 1 or no - 0):");

scanf("%d",&ch);}

while(ch==1);

printf("Directory name is:%s\n",mdname);

printf("Files names are:");

for(i=0;i<j;i++)
printf("\n%s",fname[i]);

return 0;}

SAMPLE OUTPUT:

Enter the directory name:sss

Enter the number of files:3

Enter file name to be created:aaa

Do you want to enter another file(yes - 1 or no - 0):1

Enter file name to be created:bbb

Do you want to enter another file(yes - 1 or no - 0):1

Enter file name to be created:ccc

Do you want to enter another file(yes - 1 or no - 0):0

Directory name is:sss

Files names are:

aaa

bbb

ccc

b) Two level directory

#include<string.h>

#include<stdlib.h>

#include<stdio.h>

struct{

char dname[10],fname[10][10];

int fcnt;

}dir[10];

void main(){

int i,ch,dcnt,k;

char f[30], d[30];

dcnt=0;

while(1){

printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");

printf("\n4. Search File\t\t5. Display\t6. Exit\tEnter your choice -- ");

scanf("%d",&ch);

switch(ch){

case 1: printf("\nEnter name of directory -- ");

scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;

dcnt++;

printf("Directory created");

break;

case 2: printf("\nEnter name of the directory -- ");

scanf("%s",d);

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

if(strcmp(d,dir[i].dname)==0){

printf("Enter name of the file -- ");

scanf("%s",dir[i].fname[dir[i].fcnt]);

printf("File created");

break;}

if(i==dcnt)

printf("Directory %s not found",d);

break;

case 3: printf("\nEnter name of the directory -- ");

scanf("%s",d);

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

if(strcmp(d,dir[i].dname)==0){

printf("Enter name of the file -- ");

scanf("%s",f);

for(k=0;k<dir[i].fcnt;k++){

if(strcmp(f, dir[i].fname[k])==0){

printf("File %s is deleted ",f);

dir[i].fcnt--;

strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);

goto jmp;}}

printf("File %s not found",f);

goto jmp;}}

printf("Directory %s not found",d);

jmp : break;

case 4: printf("\nEnter name of the directory -- ");

scanf("%s",d);

for(i=0;i<dcnt;i++){
if(strcmp(d,dir[i].dname)==0){

printf("Enter the name of the file -- ");

scanf("%s",f);

for(k=0;k<dir[i].fcnt;k++){

if(strcmp(f, dir[i].fname[k])==0){

printf("File %s is found ",f);

goto jmp1;}}

printf("File %s not found",f);

goto jmp1;}}

printf("Directory %s not found",d);

jmp1: break;

case 5: if(dcnt==0)

printf("\nNo Directory's ");

else{

printf("\nDirectory\tFiles");

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

printf("\n%s\t\t",dir[i].dname);

for(k=0;k<dir[i].fcnt;k++)

printf("\t%s",dir[i].fname[k]);}}

break;

default:exit(0);}}}

c) Hierarchical directory

#include<stdio.h>

#include<graphics.h>

#include<string.h>

struct tree_element{

char name[20];

int x, y, ftype, lx, rx, nc, level;

struct tree_element *link[5];};

typedef struct tree_element node;

void main(){

int gd=DETECT,gm;

node *root;
root=NULL;

create(&root,0,"root",0,639,320);

clrscr();

initgraph(&gd,&gm,"c:\tc\BGI");

display(root);

closegraph();}

create(node **root,int lev,char *dname,int lx,int rx,int x){

int i, gap;

if(*root==NULL){

(*root)=(node *)malloc(sizeof(node));

printf("Enter name of dir/file(under %s) : ",dname);

fflush(stdin);

gets((*root)->name);

printf("enter 1 for Dir/2 for file :");

scanf("%d",&(*root)->ftype);

(*root)->level=lev;

(*root)->y=50+lev*50;

(*root)->x=x;

(*root)->lx=lx;

(*root)->rx=rx;

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

(*root)->link[i]=NULL;

if((*root)->ftype==1){

printf("No of sub directories/files(for %s):",(*root)->name); scanf("%d",&(*root)>nc);

if((*root)->nc==0)

gap=rx-lx;

else

gap=(rx-lx)/(*root)->nc;

for(i=0;i<(*root)->nc;i++)

create(&((*root)>link[i]),lev+1,(*root)>name,lx+gap*i,lx+gap*i+gap,

lx+gap*i+gap/2);}

else

(*root)->nc=0;}}

display(node *root){
int i;

settextstyle(2,0,4);

settextjustify(1,1);

setfillstyle(1,BLUE);

setcolor(14);

if(root !=NULL){

for(i=0;i<root->nc;i++)

line(root->x,root->y,root->link[i]->x,root->link[i]->y);

if(root->ftype==1)

bar3d(root->x-20,root->y-10,root->x+20,root>y+10,0,0);

else

fillellipse(root->x,root->y,20,20);

outtextxy(root->x,root->y,root->name);

for(i=0;i<root->nc;i++)

display(root->link[i]);}}
Lab 19
AIM: To simulate all file allocation strategies in C

a) Sequential Allocation

THEORY: File allocation strategies determine how files are stored and accessed on a storage device, Sequential allocation is the
simplest file allocation strategy. Files are stored in a contiguous block of disk space, and each file is assigned a starting block number
when a fbutteile is read or written, the disk head moves sequentially from the beginning et the file to the end.

SOURCE CODE:

#include < stdio.h>

#include<conio.h>

int main(){

int f[50], i, st, len, j, c, k, count = 0;

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

f[i]=0;

printf("Files Allocated are : \n");

x: count=0;

printf(“Enter starting block and length of files: ”);

scanf("%d%d", &st,&len);

for(k=st;k<(st+len);k++)

if(f[k]==0)

count++;

if(len==count){

for(j=st;j<(st+len);j++)

if(f[j]==0){

f[j]=1;

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

if(j!=(st+len-1))

printf(” The file is allocated to disk\n");}

else

printf(” The file is not allocated \n");

printf("Do you want to enter more file(Yes - 1/No - 0)");

scanf("%d", &c);

if(c==1)

goto x;

else

exit();

return 0;}
SAMPLE OUTPUT:

Files Allocated are :

Enter starting block and length of files: 14 3

14 1

15 1

16 1

The file is allocated to disk

Do you want to enter more file(Yes - 1/No - 0)1

Enter starting block and length of files: 14 1

The file is not allocated

Do you want to enter more file(Yes - 1/No - 0)1

Enter starting block and length of files: 14 4

The file is not allocated

Do you want to enter more file(Yes - 1/No - 0)0

b) Linked list allocation

THEORY: Linked list file allocation is technique used in OS to manage the storage of files on disk. It works by creating a linked list
of blocks, where each block represents a portion of the file. The blocks are linked together in a chain and the OS keeps track of
location of each block, OS can allocate additional blocks as needed dynamically when file is deleted, the OS frees the blocks that were
allocated to it.

SOURCE CODE:

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

Int main(){

int f[50], p,i, st, len, j, c, k, a;

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

f[i]=0;

printf("Enter how many blocks already allocated: ");

scanf("%d",&p);

printf("Enter blocks already allocated: ");

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

scanf("%d",&a);

f[a]=1;}

x: printf("Enter index starting block and length: ");

scanf("%d%d", &st,&len);
k=len;

if(f[st]==0){

for(j=st;j<(st+k);j++){

if(f[j]==0){

f[j]=1;

printf("%d-------->%d\n",j,f[j]);}

else{

printf("%d Block is already allocated \n",j);

k++;}}}

else

printf("%d starting block is already allocated \n",st);

printf("Do you want to enter more file(Yes - 1/No - 0)");

scanf("%d", &c);

if(c==1)

goto x;

else

exit(0);

return 0;}

SAMPLE OUTPUT:

Enter how many blocks already allocated: 3

Enter blocks already allocated: 1 3 5

Enter index starting block and length: 2 2

2-------->1

3 Block is already allocated

4-------->1

Do you want to enter more file(Yes - 1/No - 0)0


Lab 20
AIM: To simulate disk scheduling algorithms in C

a) FCFS

#include<stdio.h>

int main(){

int queue[20],n,head,i,j,k,seek=0,max,diff;

float avg;

printf("Enter the max range of disk\n");

scanf("%d",&max);

printf("Enter the size of queue request\n");

scanf("%d",&n);

printf("Enter the queue of disk positions to be read\n");

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

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

printf("Enter the initial head position\n");

scanf("%d",&head);

queue[0]=head;

for(j=0;j<=n-1;j++){

diff=abs(queue[j+1]-queue[j]);

seek+=diff;

printf("Disk head moves from %d to %d with seek


%d\n",queue[j],queue[j+1],diff);}

printf("Total seek time is %d\n",seek);

avg=seek/(float)n;

printf("Average seek time is %f\n",avg);

return 0;}

b) SCAN

#include<stdio.h>

int main(){

int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],

temp1=0,temp2=0;

float avg;

printf("Enter the max range of disk\n");

scanf("%d",&max);
printf("Enter the initial head position\n");

scanf("%d",&head);

printf("Enter the size of queue request\n");

scanf("%d",&n);

printf("Enter the queue of disk positions to be read\n");

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

scanf("%d",&temp);

if(temp>=head){

queue1[temp1]=temp;

temp1++;}

Else{

queue2[temp2]=temp;

temp2++;}}

for(i=0;i<temp1-1;i++){

for(j=i+1;j<temp1;j++){

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

temp=queue1[i];

queue1[i]=queue1[j];

queue1[j]=temp;}}}

for(i=0;i<temp2-1;i++){

for(j=i+1;j<temp2;j++){

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

temp=queue2[i];

queue2[i]=queue2[j];

queue2[j]=temp;}}}

for(i=1,j=0;j<temp1;i++,j++)

queue[i]=queue1[j];

queue[i]=max;

for(i=temp1+2,j=0;j<temp2;i++,j++)

queue[i]=queue2[j];

queue[i]=0;

queue[0]=head;

for(j=0;j<=n+1;j++){

diff=abs(queue[j+1]-queue[j]);

seek+=diff;
printf("Disk head moves from %d to %d with seek
%d\n",queue[j],queue[j+1],diff);}

printf("Total seek time is %d\n",seek);

avg=seek/(float)n;

printf("Average seek time is %f\n",avg);

return 0;}

c) LOOK

#include <stdio.h>

#include <stdlib.h>

int main(){

int RQ[100],i,nj, TotalHeadMovement=0, initial, size, move;

printf("Enter the no of request: ");

scant("%d", &n);

printf("Enter the requests sequence:” );

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

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

printf("Enter initial head position: ");

scant("%d", &initial);

printf("Enter total disk size: ");

scant("%d", &size);

printf("Enter the head movement direction for high 1 and for low 0");

scanf("%d", &move”);"

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

for(j=0; j<n-i-1 ; j++){

if (RQ[j]>RQ[j+1]){

int temp;

temp=RQ[j];

RQ[j]=RQ[j+1];

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

int index;

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

if(initial<RQ[i])

index=i; break;}

if(move ==1){

for(i=index; i< n; i++){


TotalHeadMovement+=abs(RQ[i]-initial);

initial=RQ[i];}

for(i=index-1;i>=0;i--){

TotalHeadMovement+=abs(RQ[i]-initial;

initial=RQ[i];}}

else{

for(i=index-1;i>=0;i--){

TotalHeadMovement+=abs(RQ[i]-initial;

initial=RQ[i];}

for(i=index; i< n; i++){

TotalHeadMovement+=abs(RQ[i]-initial);

initial=RQ[i];}}

printf(“Total head movement is %d”,TotalHeadMovement);

return 0;}

SAMPLE OUTPUT:

Enter the number of requests: 8

Enter the requests sequence: 98 183 41 122 14 124 65 67

Enter initial head position. 53

Enter total disk size: 200

Enter the head movement direction for high 1 and for low 0: 1

Total Head Movement is 299

You might also like