Sunday, 1 November 2015

Simulation of Disk scheduling algorithms - Operating Systems

This is a single c program to simulate 5 important disk scheduling algorithms in operating systems
1.FCFS
2.SSTF
3.Scan
4.CScan
5.Look

SOURCE CODE:

#include<stdio.h>
#include<math.h>
int req[30],sreq[30];
int n,endrange;
int startpos,headpos;
int totst;
int i,j;
int choice;


void getData()
{
printf("\nEnter no. of requests:");
scanf("%d",&n);
printf("\nEnter the requests:");
for(i=0;i<n;i++)
scanf("%d",&req[i]);
printf("\n Enter the end range of head:");
scanf("%d",&endrange);
printf("\n Enter the initial position of head:");
scanf("%d",&startpos);
}

void dispTotSeekTime()
{
printf("\nTotal seek time is %d",totst);
}

void initialize()
{
totst=0;
headpos=startpos;
printf("%d ",headpos);
}

void sortRequest()
{
for(i=0;i<n;i++)
sreq[i]=req[i];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(sreq[i]>sreq[j])
{
int temp=sreq[i];
sreq[i]=sreq[j];
sreq[j]=temp;
}
}


void fcfs()
{
initialize();
for(i=0;i<n;i++)
{
totst+=abs(headpos-req[i]);
headpos=req[i];
printf("-> %d",headpos);
}
dispTotSeekTime();
}

void sstf()
{
initialize();
int visit[30];
for(i=0;i<n;i++)
visit[i]=0;
for(i=0;i<n;i++)
{
int min=endrange;
int loc;
     for(j=0;j<n;j++)
      {
        if(visit[j]==0)
         {
           if(abs(headpos-req[j])<min)
            {
              min=abs(headpos-req[j]);
              loc=j;
            }
         }
       }
totst+=min;
printf(" -> %d",req[loc]);
visit[loc]=1;
headpos=req[loc];
}
dispTotSeekTime();
}

void scan()
{
initialize();
sortRequest();
for(i=0;i<n;i++)
{
 if(headpos<sreq[i])
   {
    for(j=i-1;j>=0;j--)
      {
       totst+=abs(headpos-sreq[j]);
       headpos=sreq[j];
       printf(" -> %d",headpos);
      }
      if(choice==4)
      {
      totst+=abs(headpos-0);
      headpos=0;
      printf(" -> 0");
      }
      break;
   }
}
for(;i<n;i++)
{
totst+=abs(headpos-sreq[i]);
headpos=sreq[i];
printf(" -> %d",headpos);
}

dispTotSeekTime();
}
void cscan()
{
initialize();
sortRequest();
for(i=0;i<n;i++)
{
 if(headpos<sreq[i])
   {
    for(j=i-1;j>=0;j--)
      {
       totst+=abs(headpos-sreq[j]);
       headpos=sreq[j];
       printf(" -> %d",headpos);
      }
   
      totst+=abs(headpos-0);
      headpos=0;
      printf(" -> 0");
      headpos=endrange;
      printf(" -> %d",headpos);
      break;
   
   
   }
}
for(j=n-1;j>=i;j--)
{
totst+=abs(headpos-sreq[j]);
headpos=sreq[j];
printf(" -> %d",headpos);
}

dispTotSeekTime();
}

int main()
{

printf("\n Simulation of Disk Scheduling Algorithms ");
while(1)
{
printf("\n1.Enter data\n2.FCFS\n3.SSTF\n4.Scan\n5.C-Scan\n6.Look\n7.Exit\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
getData();
break;
case 2:
fcfs();
break;
case 3:
sstf();
break;
case 4:
case 6:
scan();
break;
case 5:
cscan();
break;
default:
return 0;
break;
}
}
}



No comments:

Post a Comment