You are on page 1of 84

OS Practical Programs

21CS2109AA- OPERATING SYSTEMS ADVANCED IN SEM LAB


EXAMINATION - PROGRAMS

1. write a c program to implement FCFS process scheduling algorithm

#include <stdio.h>
// Function to find the waiting time for all processes
int waitingtime(int proc[], int n,
int burst_time[], int wait_time[]) {
// waiting time for first process is 0
wait_time[0] = 0;
// calculating waiting time
for (int i = 1; i < n ; i++ )
wait_time[i] = burst_time[i-1] + wait_time[i-1] ;
return 0;
}
// Function to calculate turn around time
int turnaroundtime( int proc[], int n,
int burst_time[], int wait_time[], int tat[]) {
// calculating turnaround time by adding
// burst_time[i] + wait_time[i]
int i;
for ( i = 0; i < n ; i++)
tat[i] = burst_time[i] + wait_time[i];
return 0;
}
//Function to calculate average time
int avgtime( int proc[], int n, int burst_time[]) {
int wait_time[n], tat[n], total_wt = 0, total_tat = 0;
int i;
//Function to find waiting time of all processes
waitingtime(proc, n, burst_time, wait_time);
//Function to find turn around time for all processes
turnaroundtime(proc, n, burst_time, wait_time, tat);
//Display processes along with all details
printf("Processes Burst Waiting Turn around \n");
// Calculate total waiting time and total turn
// around time
for ( i=0; i<n; i++) {
total_wt = total_wt + wait_time[i];
total_tat = total_tat + tat[i];
printf(" %d\t %d\t\t %d \t%d\n", i+1, burst_time[i], wait_time[i], tat[i]);
}
printf("Average waiting time = %f\n", (float)total_wt / (float)n);
printf("Average turn around time = %f\n", (float)total_tat / (float)n);
return 0;
}
// main function
int main() {
//process id's
int proc[] = { 1, 2, 3};
int n = sizeof proc / sizeof proc[0];
//Burst time of all processes
int burst_time[] = {5, 8, 12};
avgtime(proc, n, burst_time);
return 0;
}

Output
Processes Burst Waiting Turn around
1 5 0 5
2 8 5 13
3 12 13 25
Average Waiting time = 6.000000
Average turn around time = 14.333333
Link: https://www.youtube.com/watch?v=MZdVAVMgNpA
2. Write a C program to implement SJF process scheduling algorithm.

Implementation of SJF Algorithm in C


• C
#include <stdio.h>

int main()

int A[100][4]; // Matrix for storing Process Id, Burst

// Time, Average Waiting Time & Average

// Turn Around Time.

int i, j, n, total = 0, index, temp;

float avg_wt, avg_tat;

printf("Enter number of process: ");

scanf("%d", &n);

printf("Enter Burst Time:\n");

// User Input Burst Time and alloting Process Id.

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

printf("P%d: ", i + 1);

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

A[i][0] = i + 1;

// Sorting process according to their Burst Time.

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

index = i;

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

if (A[j][1] < A[index][1])

index = j;

temp = A[i][1];
A[i][1] = A[index][1];

A[index][1] = temp;

temp = A[i][0];

A[i][0] = A[index][0];

A[index][0] = temp;

A[0][2] = 0;

// Calculation of Waiting Times

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

A[i][2] = 0;

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

A[i][2] += A[j][1];

total += A[i][2];

avg_wt = (float)total / n;

total = 0;

printf("P BT WT TAT\n");

// Calculation of Turn Around Time and printing the

// data.

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

A[i][3] = A[i][1] + A[i][2];

total += A[i][3];

printf("P%d %d %d %d\n", A[i][0],

A[i][1], A[i][2], A[i][3]);

avg_tat = (float)total / n;
printf("Average Waiting Time= %f", avg_wt);

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

Link: https://www.youtube.com/watch?v=pYO-FAg-TpQ

3. write a c program to implement round robin process scheduling


algorithm.

Write a program of round robin CPU scheduling in C


language.
1. #include<stdio.h>
2. #include<conio.h>
3.
4. void main()
5. {
6. // initlialize the variable name
7. int i, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];
8. float avg_wt, avg_tat;
9. printf(" Total number of process in the system: ");
10. scanf("%d", &NOP);
11. y = NOP; // Assign the number of process to variable y
12.
13. // Use for loop to enter the details of the process like Arrival time and the Burs
t Time
14. for(i=0; i<NOP; i++)
15. {
16. printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);
17. printf(" Arrival time is: \t"); // Accept arrival time
18. scanf("%d", &at[i]);
19. printf(" \nBurst time is: \t"); // Accept the Burst time
20. scanf("%d", &bt[i]);
21. temp[i] = bt[i]; // store the burst time in temp array
22. }
23. // Accept the Time qunat
24. printf("Enter the Time Quantum for the process: \t");
25. scanf("%d", &quant);
26. // Display the process No, burst time, Turn Around Time and the waiting time
27. printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");
28. for(sum=0, i = 0; y!=0; )
29. {
30. if(temp[i] <= quant && temp[i] > 0) // define the conditions
31. {
32. sum = sum + temp[i];
33. temp[i] = 0;
34. count=1;
35. }
36. else if(temp[i] > 0)
37. {
38. temp[i] = temp[i] - quant;
39. sum = sum + quant;
40. }
41. if(temp[i]==0 && count==1)
42. {
43. y--; //decrement the process no.
44. 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]);
45. wt = wt+sum-at[i]-bt[i];
46. tat = tat+sum-at[i];
47. count =0;
48. }
49. if(i==NOP-1)
50. {
51. i=0;
52. }
53. else if(at[i+1]<=sum)
54. {
55. i++;
56. }
57. else
58. {
59. i=0;
60. }
61. }
62. // represents the average waiting time and Turn Around time
63. avg_wt = wt * 1.0/NOP;
64. avg_tat = tat * 1.0/NOP;
65. printf("\n Average Turn Around Time: \t%f", avg_wt);
66. printf("\n Average Waiting Time: \t%f", avg_tat);
67. getch();
68. }

Output:

Link: https://www.youtube.com/watch?v=TxjIlNYRZ5M
4. Write a C program to implement Priority process scheduling
algorithm

1 #include<stdio.h>

3 int main()

4 {

5 int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;

6 printf("Enter Total Number of Process:");

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

9 printf("\nEnter Burst Time and Priority\n");

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

11 {

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

13 printf("Burst Time:");

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

15 printf("Priority:");

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

17 p[i]=i+1; //contains process number

18 }

19

20 //sorting burst time, priority and process number in ascending order using selection sort

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

22 {

23 pos=i;

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

25 {
26 if(pr[j]<pr[pos])

27 pos=j;

28 }

29

30 temp=pr[i];

31 pr[i]=pr[pos];

32 pr[pos]=temp;

33

34 temp=bt[i];

35 bt[i]=bt[pos];

36 bt[pos]=temp;

37

38 temp=p[i];

39 p[i]=p[pos];

40 p[pos]=temp;

41 }

42

43 wt[0]=0; //waiting time for first process is zero

44

45 //calculate waiting time

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

47 {

48 wt[i]=0;

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

50 wt[i]+=bt[j];

51

52 total+=wt[i];

53 }

54

55 avg_wt=total/n; //average waiting time

56 total=0;

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

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

60 {

61 tat[i]=bt[i]+wt[i]; //calculate turnaround time

62 total+=tat[i];

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

64 }

65

66 avg_tat=total/n; //average turnaround time

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

68 printf("\nAverage Turnaround Time=%d\n",avg_tat);

69

70return 0;

71}

Link: https://www.youtube.com/watch?v=rsDGfFxSgiY
5. Write C Program to simulate Multi Level Feedback Queue CPU
Scheduling algorithm.

C Program for Multilevel Feedback Queue Scheduling Algorithm

1 #include<stdio.h>

3 #define N 10

5 typedef struct

6 {

7 int process_id, arrival_time, burst_time, priority;

8 int q, ready;

9 }process_structure;

10

11 int Queue(int t1)

12 {

13 if(t1 == 0 || t1 == 1 || t1 == 2 || t1 == 3)

14 {

15 return 1;

16 }

17 else

18 {

19 return 2;

20 }

21 }

22

23 int main()

24 {
25 int limit, count, temp_process, time, j, y;

26 process_structure temp;

27 printf("Enter Total Number of Processes:\t");

28 scanf("%d", &limit);

29 process_structure process[limit];

30 for(count = 0; count < limit; count++)

31 {

32 printf("\nProcess ID:\t");

33 scanf("%d", &process[count].process_id);

34 printf("Arrival Time:\t");

35 scanf("%d", &process[count].arrival_time);

36 printf("Burst Time:\t");

37 scanf("%d", &process[count].burst_time);

38 printf("Process Priority:\t");

39 scanf("%d", &process[count].priority);

40 temp_process = process[count].priority;

41 process[count].q = Queue(temp_process);

42 process[count].ready = 0;

43 }

44 time = process[0].burst_time;

45 for(y = 0; y < limit; y++)

46 {

47 for(count = y; count < limit; count++)

48 {

49 if(process[count].arrival_time < time)

50 {

51 process[count].ready = 1;

52 }

53 }
54 for(count = y; count < limit - 1; count++)

55 {

56 for(j = count + 1; j < limit; j++)

57 {

58 if(process[count].ready == 1 && process[j].ready == 1)

59 {

60 if(process[count].q == 2 && process[j].q == 1)

61 {

62 temp = process[count];

63 process[count] = process[j];

64 process[j] = temp;

65 }

66 }

67 }

68 }

69 for(count = y; count < limit - 1; count++)

70 {

71 for(j = count + 1; j < limit; j++)

72 {

73 if(process[count].ready == 1 && process[j].ready == 1)

74 {

75 if(process[count].q == 1 && process[j].q == 1)

76 {

77 if(process[count].burst_time > process[j].burst_time)

78 {

79 temp = process[count];

80 process[count] = process[j];

81 process[j] = temp;

82 }
83 else

84 {

85 break;

86 }

87 }

88 }

89 }

90 }

91 printf("\nProcess[%d]:\tTime:\t%d To %d\n", process[y].process_id,


time, time + process[y].burst_time);
92
time = time + process[y].burst_time;
93
for(count = y; count < limit; count++)
94
{
95
if(process[count].ready == 1)
96
{
97
process[count].ready = 0;
98
}
99
}
100
}
101
return 0;
102
}
Output

Link: https://www.youtube.com/watch?v=-94WGbrWveI
6. Write C Program to simulate Multi Level Queue CPU Scheduling
algorithm.

#include<stdio.h>

int main()

int p[20],bt[20], su[20], wt[20],tat[20],i,


k, n, temp;

float wtavg, tatavg;

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

scanf("%d",&n);

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

p[i] = i;

printf("Enter the Burst Time of


Process%d:", i);

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

printf("System/User Process (0/1) ? ");

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

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

if(su[i] > su[k])

temp=p[i];

p[i]=p[k];

p[k]=temp;

temp=bt[i];

bt[i]=bt[k];

bt[k]=temp;

temp=su[i];

su[i]=su[k];

su[k]=temp;

wtavg = wt[0] = 0;

tatavg = tat[0] = bt[0];

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

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

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

wtavg = wtavg + wt[i];


tatavg = tatavg + tat[i];

printf("\nPROCESS\t\t SYSTEM/USER PROCESS


\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],su[i],bt[i],wt[i],tat[i]);

printf("\nAverage Waiting Time is ---


%f",wtavg/n);

printf("\nAverage Turnaround Time is ---


%f",tatavg/n);

return 0;

Output

The output of the above code is as follows:

Link: https://www.youtube.com/watch?v=hBPYP0ZEvS8
7. Write a C Program to simulate Multi Process Scheduling algorithm.

thalesfc Spawn a new process for each task

Latest commit 8808c3f on Aug 28, 2016 History

1 contributor

138 lines (116 sloc) 4.62 KB

RawBlame

from collections import namedtuple

from multiprocessing import SimpleQueue, Process, Condition,


Pipe

from time import sleep, time

from heapq import heappush, heappop

class Task(namedtuple('Task', 'time, fn, args')):

def __repr__(self):

return "%s(%s) @%s" % (self.fn.__name__, self.args,


self.time)

class MultiProcessScheduler:

def __init__(self):

self.cond = Condition() # default to RLock

# If duplex is False then the pipe is unidirectional

# conn1 for receiving messages and conn2 for sending


messages.

conn1, conn2 = Pipe(duplex=False)


self.connREAD = conn1

self.connWRITE = conn2

# a holder to the closest task to execute

# it is not safe to access this variable directly as

# there might be data on the pipe, use


self.__getClosestTask()

self._closestTask = None

# multiprocessing.Queue is used here to exchange task


between the add

# call and the service running __run() method

self.queue = SimpleQueue()

# dummy Process, the correct one will be created when


the first

# task is added

self.service = Process()

# TODO create destructor to avoid leaving with items on


queue

def __getClosestTask(self):

'''

return the closest task to execute (i.e., top on pq)

'''

if self.connREAD.poll():

ret = None

while self.connREAD.poll():
ret = self.connREAD.recv()

self._closestTask = ret

print("[conn] closestTaskUpdate: ",


self._closestTask)

return self._closestTask

def add(self, task):

if type(task) is not Task:

raise TypeError

self.queue.put(task)

if not self.service.is_alive():

# it seams that Process.run() is a blocking call

# so the only way to re-run the process is to


create another one

self.service = Process(

target=MultiProcessScheduler.__run,

args=(self.cond, self.queue, self.connWRITE),

daemon=False

self.service.start()

else:

# notify the condition variable if the new task


has the

# closest execution time

closestTask = self.__getClosestTask()

if closestTask and task.time < closestTask.time:

self.cond.acquire()

self.cond.notify()

self.cond.release()
@staticmethod

def __run(cond, queue, conn):

tasksQueue = []

print("[run] starting", queue.empty())

while True:

# remove tasks from queue and add to

# internal priorityQueue (tasksQueue)

while not queue.empty():

task = queue.get()

heappush(tasksQueue,task)

print("[run] adding task to pq: ", task)

# if there are task on the priority queue,

# check when the closest one should be runned

if tasksQueue:

etime, _, _ = task = tasksQueue[0]

now = time()

if etime < now:

# only pop before running

# if a task is not being running in a


given time,

# the next this loop runs that task might


not be the

# closest one

_, fn, args = heappop(tasksQueue)

print("[run] running:", task)

p = Process(target=fn, args=args,
daemon=False)
p.start()

else:

delay = etime - now

print("[run] sleeping for ", delay, task)

# send the closest task to the pipe

conn.send(task)

cond.acquire()

cond.wait(timeout=delay)

if not tasksQueue and queue.empty():

# only stop the service if there are no task


anwhere

break

print("[run] done")

if __name__ == "__main__":

# TODO move this to test/

def fnfoo(arg): print(arg)

# test 1 - the spawmed process is a not daemon process

s = MultiProcessScheduler()

print("[main] scheduler created")

# test 2.1 - wrong type of task should raise


try:

s.add('foo')

except TypeError:

pass

else:

raise Exception("add should only accept a Task")

# test 2.2 - add a valid task

print("[main] adding fn(9)")

s.add(Task(time() + 9, fnfoo, "9"))

sleep(3)

print("[main] adding fn(1)")

s.add(Task(time() + 1, fnfoo, "1"))

sleep(1)

print("[main] adding fn(2)")

s.add(Task(time() + 2, fnfoo, "2"))


8. Write a C program to simulate Lottery Process Scheduling
algorithm.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void main()
{
int n,i,j,k,temp=65,flag=0;
char process[20];
int brust[20],priority[20],pos;
int time=0,quantom=1,tbt=0;
int z=0,lottery[20],ticket[20][20],q=0;
printf("Enter Number Of Process: ");
scanf("%d",&n);
if(n<=0)
{
printf("\n\n:::: Invalid Value Of Number Of
Process ::::");
exit(0);
}
for(i=0;i<n;i++)
{
process[i] = temp;
temp+=1;
}
for(i=0;i<n;i++)
{
printf("\nEnter The Brust Time For Process %c:
",process[i]);
scanf("%d",&brust[i]);
printf("Enter The Priority For Process %c(b/w 1 to
%d): ",process[i],n);
scanf("%d",&priority[i]);
}

//sorting burst time, priority and process number in


ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(priority[j]<priority[pos])
pos=j;
}

temp=process[i];
process[i]=process[pos];
process[pos]=temp;

temp=brust[i];
brust[i]=brust[pos];
brust[pos]=temp;

temp=priority[i];
priority[i]=priority[pos];
priority[pos]=temp;

if(brust[i]<0)
{
flag = 1;
}
}

if(flag==1)
{
printf("\n\n::: Invalid Time Entered ::: \n");
exit(0);
}

printf("\n |Priority | Process | Brust |");

for(i=0;i<n;i++)
{
printf("\n | %d \t | %c \t| %d
|",priority[i],process[i],brust[i]);
tbt = tbt + brust[i];
}

printf("\n\n::::::::: Quantom time is 1 Sec :::::::::


\n\n");

//assign one or more lottery numbers to each process


int p=1,m_ticket=0;
printf("\n\n\nPriority process Brust Lottery Tickets");
for(i=0;i<n;i++)
{
lottery[i] = (brust[i]/quantom) + (n-priority[i]);
for (z=0;z<lottery[i];z++)
{
ticket[i][z] = p++;
m_ticket = p;
}

printf("\n %d\t %c\t %d \t


%d\t",priority[i],process[i],brust[i],lottery[i]);
for(z=0;z<lottery[i];z++)
{
if(ticket[i][z]<10)
printf(" ::%d:: ",ticket[i][z]);
else
printf(" ::%d::",ticket[i][z]);
}
}
while(time!=tbt)
{

int winner = (rand()%m_ticket-1)+ 1;


for(i =0;i<n;i++)
for(z=0;z<lottery[i];z++)
if(ticket[i][z]==winner)
q=i;

printf("\n\n-------------------------------------");
printf("<<<< Winner: %d >>>>",winner);
printf("-------------------------------------\n");

if ((brust[q]>0))
{
brust[q]-=quantom;

if (brust[q]>0)
{
time+=quantom;
}
else
{
time+=(brust[q]+quantom);
}

if(brust[q]<0)
{
brust[q]=0;
}
printf("\n\t\t\t\t Process That Are Running Is:
%c",process[q]);
printf("\n\t (Total Time << Remaining Brust Time Of
This Process << process ): ( %d << %d << %c
)\n",time,brust[q],process[q]);

}
else
{
printf("\n\t\t >>>>>>Related Process With This Ticket
Has Been Completed<<<<<<\n");
}

}
9. write a C program to implement Memory Fixed Partitioning
Technique (MFT) algorithm.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define inp(x) scanf("%d",&x)
#define loop(i,n) for(i=0;i<n;++i)
#define N 1000
int mm_size, free_space, n, partition_count, process_count, pid,
partid;
int i,j,k;
int parts_allocated=0;

typedef struct Process{


int pid;
int req;
bool allocated;
int partid;
int ext_frag;
int int_frag;
}Process;

typedef struct Partition{


int partid;
int size;
bool allocated;
int pid;
}Partition;

void println(){

printf("======================================================\n");
}
int alloc(int pid, Partition part[], Process pro[]){
loop(j,partition_count){
if(part[j].allocated==false && pro[i].req<=part[j].size){
//pro i in jth partition
part[j].allocated=true;
pro[i].int_frag= part[j].size - pro[i].req;
part[j].pid = pro[i].pid;
pro[i].partid = j;
free_space -= part[j].size;
printf("%d\t\t%d\t\tInternal = %d\n",i, j,
pro[i].int_frag);
++parts_allocated;
return 0;
}
}
//Could not allocate
pro[i].ext_frag = free_space;
if(free_space >= pro[i].req)
printf("%d\t\t-\t\tExternal = %d\n",i, pro[i].ext_frag);
else
printf("%d\t\t-\t\tInsufficient Memory\n",i);

}
void first_fit(Partition part[], Process pro[]){
println();
loop(i,process_count){
alloc(i, part, pro);
}
}
void dealloc(int pid, Process pro[], Partition part[]){
parts_allocated--;
partid = pro[pid].partid;
printf("Freeing Partition %d\n",partid);
pro[pid].allocated = false;
if(partid>=0 && partid<partition_count)
part[partid].allocated = false;
printf("P%d deallocated.\n",pid);
}
void initialize_pro(int i, Process pro[]){
printf("Process %d : ", i);
inp(pro[i].req);
pro[i].pid = i;
pro[i].partid = -1;
pro[i].allocated = false;
pro[i].int_frag = -1;
pro[i].ext_frag = -1;
}
int main(){
system("clear");
printf("MFT (First Fit)\n");
println();
printf("Enter Main memory size\n");
inp(mm_size);

printf("Enter no. of partitions\n");


inp(partition_count);
Partition part[partition_count];
printf("Enter size of each partitions\n");
free_space = 0;

loop(i,partition_count){
printf("Part %d : ",i);
inp(part[i].size);
part[i].allocated = false;
part[i].partid = i;
part[i].pid = -1;
free_space += part[i].size;
}
println();
if(free_space != mm_size){
printf("Sum of partitions does not match MM size\n");
return -1;
}
printf("Enter no. of processes\n");
inp(process_count);
printf("Enter memory reqd for \n");
Process pro[N];
loop(i,process_count){
initialize_pro(i, pro);
}

println();
printf("\nPID\t\tPartID\t\tIssues/Fragments\n");
first_fit(part, pro);

again:
printf("\nPress 1 to add more : ");
inp(i);
println();
if(i!=1)
return 0;
if(parts_allocated == partition_count){
printf("Partitions Full\nEnter PID to remove from memory :
");
inp(pid);
dealloc(pid, pro, part);
}
i = process_count++;
printf("Enter size\n");
initialize_pro(i,pro);
alloc(i, part, pro);
goto again;
return 0;
}
[vishnu@os memory]$ cc mft.c
[vishnu@os memory]$ ./a.out
MFT (First Fit)
======================================================
Enter Main memory size
10
Enter no. of partitions
5
Enter size of each partitions
Part 0 : 1
Part 1 : 1
Part 2 : 2
Part 3 : 2
Part 4 : 4
======================================================
Enter no. of processes
4
Enter memory reqd for
Process 0 : 1
Process 1 : 1
Process 2 : 1
Process 3 : 1
======================================================

PID PartID Issues/Fragments


======================================================
0 0 Internal = 0
1 1 Internal = 0
2 2 Internal = 1
3 3 Internal = 1

Press 1 to add more : 1


======================================================
Enter size
Process 4 : 4
4 4 Internal = 0

Press 1 to add more : 1


======================================================
Partitions Full
Enter PID to remove from memory : 4
Freeing Partition 4
P4 deallocated.
Enter size
Process 5 : 4
5 4 Internal = 0

Press 1 to add more : 1


======================================================
Partitions Full
10. write a C program to implement Memory Variable
Partitioning Technique (MVT) algorithm.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define inp(x) scanf("%d",&x)
#define loop(i,n) for(i=0;i<n;++i)
#define N 1000
int mm_size, slot_count = 1, pid = -1, pos=0, free_mem, pid_del;
int i, j, k;
int parts_allocated=0;

typedef struct Process{


int pid;
int req;
bool allocated;
}Process;

typedef struct Slots{


int pid;
int start;
int end;
int size;
bool empty;
}Slots;
Slots slots[N];
Process pro[N];

void println(){

printf("======================================================\n");
}

void mem_table(){
println();
printf("Memory Contents\n");
println();
printf("Size\t\tContents\t\tRange\n");
loop(i,slot_count){
printf("%d\t\t",slots[i].size);
(slots[i].pid==-1) ? printf("-\t\t\t%d-
%d\n",slots[i].start,slots[i].end) :
printf("P%d\t\t\t%d-
%d\n",slots[i].pid,slots[i].start,slots[i].end);

}
println();
}
int find_slot(){
for(i=0; i<slot_count; i++)
if(slots[i].pid==-1 && slots[i].size >=
pro[pid].req)
return i;

return -1;
}
void alloc(int pos)
{
//Move everything to right to create a slot at pos
for(i=slot_count; i>pos; i--)
slots[i] = slots[i-1];

slots[pos].pid = pid;
slots[pos].size = pro[pid].req;
pro[pid].allocated = true;
slots[pos].empty == false;
slots[pos].start == (pos==0)?0:slots[pos+1].end;
slots[pos].end= slots[pos].start+ slots[pos].size;
free_mem -= pro[pid].req;
//Decrease req from the chosen chunk
slots[pos+1].size -= pro[pid].req;
slots[pos+1].start += pro[pid].req;
slot_count++;
}

int dealloc_merge(int slot_del)


{
slots[slot_del].empty=true;
slots[slot_del].pid=-1;
free_mem += slots[slot_del].size;
//If right slot free merge
if(slot_del!=slot_count-1 && slots[slot_del+1].pid==-1)
{
slots[slot_del].size += slots[slot_del+1].size;
for(i=slot_del+1; i<slot_count-1; i++)
slots[i] = slots[i+1];
slot_count--;
}
//If left slot free merge
if(slot_del>0 && slots[slot_del-1].pid==-1)
{
slots[slot_del-1].size += slots[slot_del].size;
for(i=slot_del; i<slot_count-1; i++)
slots[i] = slots[i+1];
slot_count--;
}
}
int main(){
system("clear");
printf("MVT\n");
println();
printf("Enter Main memory size\n");
inp(mm_size);
free_mem = mm_size;
//Initially One free chunk of mem
slots[0].pid = -1;
slots[0].size = mm_size;
slots[0].start = 0;
slots[0].end = mm_size;
//slots[0].empty = true;
mem_table();
again:
printf("1. Allocate\t\t2. Deallocate\n");
inp(k);
if(k==1){
pid++;
pro[pid].pid = pid;
pro[pid].allocated = false;
printf("Mem for P%d : ", pid);
inp(pro[pid].req);
pos = find_slot();
//printf("Slot %d found for P%d\n",pos,pid);
if(pos == -1){
if(free_mem < pro[pid].req)
printf("Insufficient Memory\n");
else
printf("Cannot Allocate\nExternal Fragment =
%d\n",free_mem);
}
else
alloc(pos);//At given slot position
}
else if(k==2){
printf("Enter PID to remove : ");
inp(pid_del);

loop(i, slot_count)
if(slots[i].pid == pid_del){
dealloc_merge(i);
break;
}
}
else
return 0;
mem_table();
goto again;
return 0;
}
[vishnu@os memory]$ cc mvt.c
[vishnu@os memory]$ ./a.out
MVT
======================================================
Enter Main memory size
32
======================================================
Memory Contents
======================================================
Size Contents Range
32 - 0-32
======================================================
1. Allocate 2. Deallocate
1
Mem for P0 : 10
======================================================
Memory Contents
======================================================
Size Contents Range
10 P0 0-10
22 - 10-32
======================================================
1. Allocate 2. Deallocate
1
Mem for P1 : 20
======================================================
Memory Contents
======================================================
Size Contents Range
10 P0 0-10
20 P1 10-30
2 - 30-32
======================================================
1. Allocate 2. Deallocate
1
Mem for P2 : 3
Insufficient Memory
======================================================
Memory Contents
======================================================
Size Contents Range
10 P0 0-10
20 P1 10-30
2 - 30-32
======================================================
1. Allocate 2. Deallocate
2
Enter PID to remove : 1
======================================================
Memory Contents
======================================================
Size Contents Range
10 P0 0-10
22 - 10-30
======================================================
1. Allocate 2. Deallocate

Link:
https://www.youtube.com/watch?v=JdPmsrYqRDY&t=571s
11 write a program to simulate Dynamic Memory Allocation
in C using malloc().
12 write a program to simulate Dynamic Memory Allocation
in C using calloc().
13 write a program to simulate Dynamic Memory Allocation
in C using free().
14 write a program to simulate Dynamic Memory Allocation
in C using realloc().

Link: https://github.com/RAGUL1902/Dynamic-Memory-
Allocation-in-C#freec

15. Refer 10 Question.

16. write a C program to implement Memory Management


concept using the technique best fit.

#include<stdio.h>

void main()
{
int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999;
static int barray[20],parray[20];
printf("\n\t\t\tMemory Management Scheme - Best Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of processes:");
scanf("%d",&np);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block no.%d:",i);
scanf("%d",&b[i]);
}
printf("\nEnter the size of the processes :-\n");
for(i=1;i<=np;i++)
{
printf("Process no.%d:",i);
scanf("%d",&p[i]);
}
for(i=1;i<=np;i++)
{
for(j=1;j<=nb;j++)
{
if(barray[j]!=1)
{
temp=b[j]-p[i];
if(temp>=0)
if(lowest>temp)
{
parray[i]=j;
lowest=temp;
}
}
}
fragment[i]=lowest;
barray[parray[i]]=1;
lowest=10000;
}
printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");
for(i=1;i<=np && parray[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,p[i],parray[i],b[parray[i]],fragment[i]);
}

17. write a C program to implement Memory Management


concept using the technique worst fit .

/ C++ implementation of worst - Fit algorithm


#include<bits/stdc++.h>
using namespace std;

// Function to allocate memory to blocks as per worst fit


// algorithm
void worstFit(int blockSize[], int m, int processSize[],
int n)
{
// Stores block id of the block allocated to a
// process
int allocation[n];

// Initially no block is assigned to any process


memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i=0; i<n; i++)
{
// Find the best fit block for current process
int wstIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (wstIdx == -1)
wstIdx = j;
else if (blockSize[wstIdx] < blockSize[j])
wstIdx = j;
}
}

// If we could find a block for current process


if (wstIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = wstIdx;

// Reduce available memory in this block.


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

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] <<
"\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);

worstFit(blockSize, m, processSize, n);


return 0 ;
}

18. write a C program to implement Memory Management


concept using the technique first fit.
// C implementation of First - Fit algorithm
#include<stdio.h>

// Function to allocate memory to


// blocks as per First fit algorithm
void firstFit(int blockSize[], int m, int processSize[], int n)
{
int i, j;
// Stores block id of the
// block allocated to a process
int allocation[n];

// Initially no block is assigned to any process


for(i = 0; i < n; i++)
{
allocation[i] = -1;
}

// pick each process and find suitable blocks


// according to its size ad assign to it
for (i = 0; i < n; i++) //here, n -> number of
processes
{
for (j = 0; j < m; j++) //here, m -> number of
blocks
{
if (blockSize[j] >= processSize[i])
{
// allocating block j to the ith process
allocation[i] = j;

// Reduce available memory in this block.


blockSize[j] -= processSize[i];

break; //go to the next process in the queue


}
}
}

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

// Driver code
int main()
{
int m; //number of blocks in the memory
int n; //number of processes in the input queue
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 ;
}
Link: https://www.youtube.com/watch?v=N3rG_1CEQkQ

19. write a C program to implement paging concept for


memory management.

#include<stdio.h>
#define MAX 50
int main()
{
int page[MAX],i,n,f,ps,off,pno;
int choice=0;
printf("\nEnter the no of peges in memory: ");
scanf("%d",&n);
printf("\nEnter page size: ");
scanf("%d",&ps);
printf("\nEnter no of frames: ");
scanf("%d",&f);
for(i=0;i<n;i++)
page[i]=-1;
printf("\nEnter the page table\n");
printf("(Enter frame no as -1 if that page is not present in any frame)\n\n");
printf("\npageno\tframeno\n-------\t-------");
for(i=0;i<n;i++)
{
printf("\n\n%d\t\t",i);
scanf("%d",&page[i]);
}
do
{
printf("\n\nEnter the logical address(i.e,page no & offset):");
scanf("%d%d",&pno,&off);
if(page[pno]==-1)
printf("\n\nThe required page is not available in any of frames");
else
printf("\n\nPhysical address(i.e,frame no & offset):%d,%d",page[pno],off);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
return 1;
}
Output:

Link: https://www.youtube.com/watch?v=6c-mOFZwP_8
20. write a C program for Static Memory Allocation.

// C program to implement
// static memory allocation
#include <stdio.h>
#include <stdlib.h>

// Driver code
int main()
{
int size;
printf("Enter limit of the text: \n");
scanf("%d", &size);
char str[size];
printf("Enter some text: \n");
scanf(" ");
gets(str);
printf("Inputted text is: %s\n", str);
return 0;
}

Input:

Output:
21. write a C program for Dynamic Memory Allocation.

Below is the C program to illustrate the Dynamic Memory Allocation:

• C

// C program to illustrate the above


// concepts of memory allocation
#include <stdio.h>
#include <stdlib.h>

// Driver Code
int main()
{
int size, resize;
char* str = NULL;
printf("Enter limit of the "
"text: \n");
scanf("%d", &size);

str = (char*)malloc(size * sizeof(char));

// If str is not NULL


if (str != NULL) {
printf("Enter some text: \n");
scanf(" ");
gets(str);
printf("Inputted text by allocating"
"memory using malloc() is: "
"%s\n",
str);
}

// Free the memory


free(str);
str = (char*)calloc(50, sizeof(char));

// If str is not NULL


if (str != NULL) {
printf("Enter some text: \n");
scanf(" ");
gets(str);
printf("Inputted text by allocating "
"memory using calloc() is: "
"%s\n",
str);
}

printf("Enter the new size: \n");


scanf("%d", &resize);
str = (char*)realloc(str, resize * sizeof(char));

printf("Memory is successfully "


"reallocated by using "
"realloc() \n");

// If str is not NULL


if (str != NULL) {
printf("Enter some text: \n");
scanf(" ");
gets(str);
printf("Inputted text by reallocating"
" memory using realloc()is: "
"%s\n",
str);
}

// Free the memory


free(str);
str = NULL;

return 0;
}

Input:

Output:
22. write a C program to implement FIFO page replacement
algorithm.

FIFO Page Replacement Algorithm in C


Run

// C program for FIFO page replacement algorithm


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

Link: https://www.youtube.com/watch?v=8rcUs5RutX0
23. write a C program to implement LRU page replacement
algorithm.

LRU program in C (Method 1 : Better)


Run

#include<stdio.h>
#include<limits.h>

int checkHit(int incomingPage, int queue[], int occupied){

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


if(incomingPage == queue[i])
return 1;
}

return 0;
}

void printFrame(int queue[], int occupied)


{
for(int i = 0; i < occupied; i++)
printf("%d\t\t\t",queue[i]);
}

int main()
{

// int incomingStream[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1};


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

int n = sizeof(incomingStream)/sizeof(incomingStream[0]);
int frames = 3;
int queue[n];
int distance[n];
int occupied = 0;
int pagefault = 0;

printf("Page\t Frame1 \t Frame2 \t Frame3\n");

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


{
printf("%d: \t\t",incomingStream[i]);
// what if currently in frame 7
// next item that appears also 7
// didnt write condition for HIT

if(checkHit(incomingStream[i], queue, occupied)){


printFrame(queue, occupied);
}

// filling when frame(s) is/are empty


else if(occupied < frames){
queue[occupied] = incomingStream[i];
pagefault++;
occupied++;

printFrame(queue, occupied);
}
else{

int max = INT_MIN;


int index;
// get LRU distance for each item in frame
for (int j = 0; j < frames; j++)
{
distance[j] = 0;
// traverse in reverse direction to find
// at what distance frame item occurred last
for(int k = i - 1; k >= 0; k--)
{
++distance[j];

if(queue[j] == incomingStream[k])
break;
}

// find frame item with max distance for LRU


// also notes the index of frame item in queue
// which appears furthest(max distance)
if(distance[j] > max){
max = distance[j];
index = j;
}
}
queue[index] = incomingStream[i];
printFrame(queue, occupied);
pagefault++;
}

printf("\n");
}

printf("Page Fault: %d",pagefault);

return 0;
}

Output –

Page Frame1 Frame2 Frame3


1: 1
2: 1 2
3: 1 2 3
2: 1 2 3
1: 1 2 3
5: 1 2 5
2: 1 2 5
1: 1 2 5
6: 1 2 6
2: 1 2 6
5: 5 2 6
6: 5 2 6
3: 5 3 6
1: 1 3 6
3: 1 3 6
Page Fault: 8

LRU program in C (Method 2)


Run

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

Output –

1: 1 -1 -1
2: 1 2 -1
3: 1 2 3
2: 1 2 3
1: 1 2 3
5: 1 2 5
2: 1 2 5
1: 1 2 5
6: 1 2 6
2: 1 2 6
5: 5 2 6
6: 5 2 6
3: 5 3 6
1: 1 3 6
3: 1 3 6
6: 1 3 6
1: 1 3 6
2: 1 2 6
4: 1 2 4
3: 3 2 4

Total Number of Page Faults: 11

Link: https://www.youtube.com/watch?v=dYIoWkCvd6A
24. Write a C program to simulate Optimal page replacement
algorithms.

// Java program to demonstrate optimal page


// replacement algorithm.
import java.io.*;
import java.util.*;

class GFG {

// Function to check whether a page exists


// in a frame or not
static boolean search(int key, int[] fr)
{
for (int i = 0; i < fr.length; i++)
if (fr[i] == key)
return true;
return false;
}

// Function to find the frame that will not be used


// recently in future after given index in pg[0..pn-1]
static int predict(int pg[], int[] fr, int pn,
int index)
{
// Store the index of pages which are going
// to be used recently in future
int res = -1, farthest = index;
for (int i = 0; i < fr.length; i++) {
int j;
for (j = index; j < pn; j++) {
if (fr[i] == pg[j]) {
if (j > farthest) {
farthest = j;
res = i;
}
break;
}
}

// If a page is never referenced in future,


// return it.
if (j == pn)
return i;
}

// If all of the frames were not in future,


// return any of them, we return 0. Otherwise
// we return res.
return (res == -1) ? 0 : res;
}

static void optimalPage(int pg[], int pn, int fn)


{
// Create an array for given number of
// frames and initialize it as empty.
int[] fr = new int[fn];

// Traverse through page reference array


// and check for miss and hit.
int hit = 0;
int index = 0;
for (int i = 0; i < pn; i++) {

// Page found in a frame : HIT


if (search(pg[i], fr)) {
hit++;
continue;
}

// Page not found in a frame : MISS

// If there is space available in frames.


if (index < fn)
fr[index++] = pg[i];

// Find the page to be replaced.


else {
int j = predict(pg, fr, pn, i + 1);
fr[j] = pg[i];
}
}
System.out.println("No. of hits = " + hit);
System.out.println("No. of misses = " + (pn - hit));
}

// driver function
public static void main(String[] args)
{

int pg[]
= { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 };
int pn = pg.length;
int fn = 4;
optimalPage(pg, pn, fn);
}
}

Link: https://www.youtube.com/watch?v=AyEf36TlQjU

25. Write a C program to simulate LFU page replacement


algorithms.

LFU PAGE REPLACEMENT ALGORITHM


#include<stdio.h>
#include<conio.h>
main()
{
int rs[50], i, j, k, m, f, cntr[20], a[20], min, pf=0;
clrscr();
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("\n\n Total number of page faults -- %d",pf);
getch();
}

INPUT
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

OUTPUT
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
5 2 3
5 2 3
5 2 1 PF No. 6
5 2 4 PF No. 7
5 2 3 PF No. 8

Total number of page faults -- 8


Link: https://www.youtube.com/watch?v=Q_et1_FpMrE

26. Write a C program to implement FCFS Disk Scheduling


Algorithm.

// Java program to demonstrate


// FCFS Disk Scheduling algorithm
class GFG
{
static int size = 8;

static void FCFS(int arr[], int head)


{
int seek_count = 0;
int distance, cur_track;

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


{
cur_track = arr[i];

// calculate absolute distance


distance = Math.abs(cur_track - head);

// increase the total count


seek_count += distance;

// accessed track is now new head


head = cur_track;
}

System.out.println("Total number of " +


"seek operations = " +
seek_count);

// Seek sequence would be the same


// as request array sequence
System.out.println("Seek Sequence is");

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


{
System.out.println(arr[i]);
}
}

// Driver code
public static void main(String[] args)
{
// request array
int arr[] = { 176, 79, 34, 60,
92, 11, 41, 114 };
int head = 50;

FCFS(arr, head);
}
}

// This code is contributed by 29AjayKumar

Output:
Total number of seek operations = 510
Seek Sequence is
176
79
34
60
92
11
41
114

Link: https://www.youtube.com/watch?v=yP89YlEGCqA
27. Write a C program to implement SCAN Disk scheduling
algorithm.

// C Program to Simulate SCAN Disk Scheduling Algorithm


//visit www.nanogalaxy.org for more programs.

#include<stdio.h>
int absoluteValue(int); // Declaring function absoluteValue

void main()
{
int queue[25],n,headposition,i,j,k,seek=0, maxrange,
difference,temp,queue1[20],queue2[20],temp1=0,temp2=0;
float averageSeekTime;

// Reading the maximum Range of the Disk.


printf("Enter the maximum range of Disk: ");
scanf("%d",&maxrange);

// Reading the number of Queue Requests(Disk access requests)


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

// Reading the initial head position.(ie. the starting point of


execution)
printf("Enter the initial head position: ");
scanf("%d",&headposition);

// Reading disk positions to be read in the order of arrival


printf("Enter the disk positions to be read(queue): ");
for(i=1;i<=n;i++) // Note that i varies from 1 to n instead of
0 to n-1
{
scanf("%d",&temp); //Reading position value to a temporary
variable

//Now if the requested position is greater than current


headposition,
//then pushing that to array queue1
if(temp>headposition)
{
queue1[temp1]=temp; //temp1 is the index variable of
queue1[]
temp1++; //incrementing temp1
}
else //else if temp < current headposition,then push to
array queue2[]
{
queue2[temp2]=temp; //temp2 is the index variable of
queue2[]
temp2++;
}
}

//Now we have to sort the two arrays


//SORTING array queue1[] in ascending order
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;
}
}
}

//SORTING array queue2[] in descending order


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

//Copying first array queue1[] into queue[]


for(i=1,j=0;j<temp1;i++,j++)
{
queue[i]=queue1[j];
}

//Setting queue[i] to maxrange because the head goes to


//end of disk and comes back in scan Algorithm
queue[i]=maxrange;

//Copying second array queue2[] after that first one is copied,


into queue[]
for(i=temp1+2,j=0;j<temp2;i++,j++)
{
queue[i]=queue2[j];
}

//Setting queue[i] to 0. Because that is the innermost cylinder.


queue[i]=0;
//At this point, we have the queue[] with the requests in the
//correct order of execution as per scan algorithm.
//Now we have to set 0th index of queue[] to be the initial
headposition.
queue[0]=headposition;

// Calculating SEEK TIME. seek is initially set to 0 in the


declaration part.

for(j=0; j<=n; j++) //Loop starts from headposition. (ie. 0th


index of queue)
{
// Finding the difference between next position and current
position.
difference = absoluteValue(queue[j+1]-queue[j]);

// Adding difference to the current seek time value


seek = seek + difference;

// Displaying a message to show the movement of disk head


printf("Disk head moves from position %d to %d with Seek %d
\n",
queue[j], queue[j+1], difference);
}

// Calculating Average Seek time


averageSeekTime = seek/(float)n;

//Display Total and Average Seek Time(s)


printf("Total Seek Time= %d\n", seek);
printf("Average Seek Time= %f\n", averageSeekTime);
}

// Defining function absoluteValue


int absoluteValue(int x)
{
if(x>0)
{
return x;
}
else
{
return x*-1;
}
}

// END OF CODE
//Code written and commented by Nived Kannada
Output

Link: https://www.youtube.com/watch?v=xouo556RGiE

28. Write a C program to implement C-SCAN Disk scheduling


algorithm.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int RQ[100],i,j,n,TotalHeadMoment=0,initial,size,move;
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);
printf("Enter total disk size\n");
scanf("%d",&size);
printf("Enter the head movement direction for high 1 and for low
0\n");
scanf("%d",&move);

// logic for C-Scan disk scheduling

/*logic for sort the request array */


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 movement is towards high value


if(move==1)
{
for(i=index;i<n;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}
// last movement for max size
TotalHeadMoment=TotalHeadMoment+abs(size-RQ[i-1]-1);
/*movement max to min disk */
TotalHeadMoment=TotalHeadMoment+abs(size-1-0);
initial=0;
for( i=0;i<index;i++)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];

}
}
// if movement is towards low value
else
{
for(i=index-1;i>=0;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];
}
// last movement for min size
TotalHeadMoment=TotalHeadMoment+abs(RQ[i+1]-0);
/*movement min to max disk */
TotalHeadMoment=TotalHeadMoment+abs(size-1-0);
initial =size-1;
for(i=n-1;i>=index;i--)
{
TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);
initial=RQ[i];

}
}

printf("Total head movement is %d",TotalHeadMoment);


return 0;
}
Output:-

Enter the number of Request


8
Enter the Requests Sequence
95 180 34 119 11 123 62 64
Enter initial head position
50
Enter total disk size
200
Enter the head movement direction for high 1 and for low 0
1
Total head movement is 382

Link: https://www.youtube.com/watch?v=vLqZ6ZMBkX8

29. Write a Program C-LOOK Disk Scheduling Algorithm in C.

// Java implementation of the approach


import java.util.*;

class GFG{

static int size = 8;


static int disk_size = 200;

// Function to perform C-LOOK on the request


// array starting from the given head
public static void CLOOK(int arr[], int head)
{
int seek_count = 0;
int distance, cur_track;

Vector<Integer> left = new Vector<Integer>();


Vector<Integer> right = new Vector<Integer>();
Vector<Integer> seek_sequence = new Vector<Integer>();

// Tracks on the left of the


// head will be serviced when
// once the head comes back
// to the beginning (left end)
for(int i = 0; i < size; i++)
{
if (arr[i] < head)
left.add(arr[i]);
if (arr[i] > head)
right.add(arr[i]);
}

// Sorting left and right vectors


Collections.sort(left);
Collections.sort(right);

// First service the requests


// on the right side of the
// head
for(int i = 0; i < right.size(); i++)
{
cur_track = right.get(i);

// Appending current track


// to seek sequence
seek_sequence.add(cur_track);

// Calculate absolute distance


distance = Math.abs(cur_track - head);

// Increase the total count


seek_count += distance;

// Accessed track is now new head


head = cur_track;
}

// Once reached the right end


// jump to the last track that
// is needed to be serviced in
// left direction
seek_count += Math.abs(head - left.get(0));
head = left.get(0);

// Now service the requests again


// which are left
for(int i = 0; i < left.size(); i++)
{
cur_track = left.get(i);

// Appending current track to


// seek sequence
seek_sequence.add(cur_track);

// Calculate absolute distance


distance = Math.abs(cur_track - head);

// Increase the total count


seek_count += distance;

// Accessed track is now the new head


head = cur_track;
}

System.out.println("Total number of seek " +


"operations = " + seek_count);

System.out.println("Seek Sequence is");

for(int i = 0; i < seek_sequence.size(); i++)


{
System.out.println(seek_sequence.get(i));
}
}

// Driver code
public static void main(String []args)
{

// Request array
int arr[] = { 176, 79, 34, 60,
92, 11, 41, 114 };
int head = 50;

System.out.println("Initial position of head: " +


head);

CLOOK(arr, head);
}
}

// This code is contributed by divyesh072019

Output:
Initial position of head: 50
Total number of seek operations = 321
Seek Sequence is
60
79
92
114
176
11
34
41

Link: https://www.youtube.com/watch?v=gwCgG5ORXW8

30. Write a C Program to implement SSTF Disk scheduling


algorithm.

Code:-

#include<stdio.h>
#include<stdlib.h>
int main()
{
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;
count++;
}

printf("Total head movement is %d",TotalHeadMoment);


return 0;
}

Output:-

Enter the number of Request


8
Enter Request Sequence
95 180 34 119 11 123 62 64
Enter initial head Position
50
Total head movement is 236

Link: https://www.youtube.com/watch?v=P_dA8VGJjA8
31. Write an algorithm to implement SCAN Disk scheduling
algorithm.

Link: https://www.youtube.com/watch?v=xouo556RGiE

32. Write a C program to organize the file using single level


directory.

/* Program to simulate single level directory


*/
Program Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int nf=0,i=0,j=0,ch;
char mdname[10],fname[10][10],name[10];
clrscr();
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]);
getch();
}

Program 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

Link: https://www.youtube.com/watch?v=DKzSGo9b28Q

33. Write a C program to organize the file using two level


directory.

Program to simulate Two


level file organization
technique
BY · PUBLISHED OCTOBER 21, 2019 · UPDATED JULY 25, 2021

#include
#include
struct st
{
char dname[10];
char sdname[10][10];
char fname[10][10][10];
int ds,sds[10];
}dir[10];
void main()
{
int i,j,k,n;
clrscr();
printf("enter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)< span="" style="box-sizing: border-box;">
{
printf("enter directory %d names:",i+1);
scanf("%s",&dir[i].dname);
printf("enter size of directories:");
scanf("%d",&dir[i].ds);
for(j=0;j<dir[i].ds;j++)< span="" style="box-sizing: border-box;">
{
printf("enter subdirectory name and size:");
scanf("%s",&dir[i].sdname[j]);
scanf("%d",&dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)< span="" style="box-sizing: border-box;">
{
printf("enter file name:");
scanf("%s",&dir[i].fname[j][k]);
}
}
}
printf("\ndirname\t\tsize\tsubdirname\tsize\tfiles");
printf("\n******************************************************\n");
for(i=0;i<n;i++)< span="" style="box-sizing: border-box;">
{
printf("%s\t\t%d",dir[i].dname,dir[i].ds);
for(j=0;j<dir[i].ds;j++)< span="" style="box-sizing: border-box;">
{
printf("\t%s\t\t%d\t",dir[i].sdname[j],dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)< span="" style="box-sizing: border-box;">

printf("%s\t",dir[i].fname[j][k]);
printf("\n\t\t");
}
printf("\n");
}
getch();
}
</dir[i].sds[j];k++)<></dir[i].ds;j++)<></n;i++)<></dir[i].sds[j];k++)<></dir[
i].ds;j++)<></n;i++)<>

34. Write program to Implementation Sequential file


allocation.

/* Program to simulate sequential file


allocation strategy */
Program Code:
#include < stdio.h>
#include<conio.h>
void main()
{
int f[50], i, st, len, j, c, k, count = 0;
clrscr();
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();
getch();
}
Program 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

Link: https://www.youtube.com/watch?v=dNwdZs0iWWU
35. Write program to Implementation indexed file allocation.

Algorithm for Indexed File Allocation:


Step 1: Start.
Step 2: Let n be the size of the buffer
Step 3: check if there are any producer
Step 4: if yes check whether the buffer is full
Step 5: If no the producer item is stored in the
buffer
Step 6: If the buffer is full the producer has to wait
Step 7: Check there is any consumer.If yes check
whether the buffer is empty
Step 8: If no the consumer consumes them from the
buffer
Step 9: If the buffer is empty, the consumer has to
wait.
Step 10: Repeat checking for the producer and
consumer till required
Step 11: Terminate the process.
/* Program to simulate indexed file
allocation strategy */
Program Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int f[50], index[50],i, n, st, len, j, c, k, ind,count=0;
clrscr();
for(i=0;i<50;i++)
f[i]=0;
x:printf("Enter the index block: ");
scanf("%d",&ind);
if(f[ind]!=1)
{
printf("Enter no of blocks needed and no of files for
the index %d on the disk : \n", ind);
scanf("%d",&n);
}
else
{
printf("%d index is already allocated \n",ind);
goto x;
}
y: count=0;
for(i=0;i<n;i++)
{
scanf("%d", &index[i]);
if(f[index[i]]==0)
count++;
}
if(count==n)
{
for(j=0;j<n;j++)
f[index[j]]=1;
printf("Allocated\n");
printf("File Indexed\n");
for(k=0;k<n;k++)
printf("%d-------->%d :
%d\n",ind,index[k],f[index[k]]);
}
else
{
printf("File in the index is already allocated \n");
printf("Enter another file indexed");
goto y;
}
printf("Do you want to enter more file(Yes - 1/No -
0)");
scanf("%d", &c);
if(c==1)
goto x;
else
exit(0);
getch();
}

Program Output:
Enter the index block: 5
Enter no of blocks needed and no of files for the
index 5 on the disk :
4
1234
Allocated
File Indexed
5-------->1 : 1
5-------->2 : 1
5-------->3 : 1
5-------->4 : 1
Do you want to enter more file(Yes - 1/No - 0)1
Enter the index block: 4
4 index is already allocated
Enter the index block: 6
Enter no of blocks needed and no of files for the
index 6 on the disk :
2
78
A5llocated
File Indexed
6-------->7 : 1
6-------->8 : 1
Do you want to enter more file(Yes - 1/No - 0)0

Link:
https://www.youtube.com/watch?v=S6lLRz7SQU
w
36. Write program to Implementation linked file allocation.

Program to implement
linked file allocation
technique.
BY · PUBLISHED OCTOBER 21, 2019 · UPDATED OCTOBER 21, 2019
Concept: In the chained method file allocation table contains a field which
points to starting block of memory. From it for each bloc a pointer is kept to
next successive block. Hence, there is no external fragmentation
ALGORTHIM:
Step 1: Start
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations by selecting a location randomly q=
random(100);
a) Check whether the selected location is free .
b) If the location is free allocate and set flag=1 to the allocated locations.
While allocating next location address to attach it to previous location
for(i=0;i0)
{
}
}
p=r[i][j-1];
b[p].next=q;
}
Step 5: Print the results file no, length ,Blocks allocated.
Step 6: Stop

#include
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++)< span="" style="box-sizing: border-box;">
{
scanf("%d",&a);
f[a]=1;
}
X:
printf("Enter the starting index block & length");
scanf("%d%d",&st,&len);
k=len;
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{
f[j]=1;

printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d->file is already allocated",j);
k++;
}
}
printf("\n If u want to enter one more file? (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit();
getch( );
}
</p;i++)<>
OUTPUT:
Enter how many blocks that 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->1 file is already allocated
5->1
6->1
7->1 file is already allocated
8->1
9->1file is already allocated
10->1
11->1
12->1

Link: https://www.youtube.com/watch?v=irGdM3iIS54

37. Write C program to Implement Continuous file allocation


strategy.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
int start[10],num=0,count=0,length[10],j,f=1,i=0;
char name[20][10];
char del[2];
int ch=0;
while(1){
printf("Contiguous file allocation\n");
printf("1.File Creation\n");
printf("2.File Deletion\n");
printf("3.Display File Allocation Table\n");
printf("4.Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch){
case 1:
printf("Enter the name of the file\n");
scanf("%s",&name[i][0]);
printf("Enter the start block of the file\n");
scanf("%d",&start[i]);
printf("Enter the length of the file\n");
scanf("%d",&length[i]);
num++;
i++;
if(f==1){
f++;
}
for(j=0;j<num;j++){
if(start[j+1]<=start[j] || start[j+1]>=length[j]){

}
else{
count++;
}
}
if(count==1){
printf("%s cannot be allocated disk space\n",name[i-1
]);
}
else{
printf("file %s allocated disk space\n",name[i-1]);
}
break;
case 2:
printf("Enter the name of the file to be deleted\n");
scanf("%s",&del[0]);
printf("file %s deleted\n",&del[0]);
f--;
f--;
break;
case 3:
printf("File Allocation Table\n");
printf("File Name Start Block Length\n");
if(f==2){
printf("%s %d %d\n",name[0],start[0],length[0]);
}
for(int k=0,n=1;k<num && n<num ;k++,n++){
if(start[k+1]<=start[k] || start[k+1]>=length[k]){
printf("%s %d %d\n",name[n],start[n],length[n]);
}
}
break;
case 4:
exit(1);
default:
printf("invalid");
}
getchar();
}
return 0;
}

Link: https://www.youtube.com/watch?v=XHx-ms5Ldi4

You might also like