Showing posts with label os. Show all posts
Showing posts with label os. Show all posts

Thursday, 26 November 2015

C program for deadlock detection - Operating Systems

ALGORITHM:

1. Mark each process that has a row in the Allocation matrix of all zeros.
2. Initialize a temporary vectorW to equal the Available vector.
3. Find an indexi such that processi is currently unmarked and thei th row ofQ
is less than or equal to W . That is,Q ik Wk, for 1 … k m . If no such row is
found, terminate the algorithm.
4. If such a row is found, mark processi and add the corresponding row of the
allocation matrix to W . That is, setWk = Wk + Aik, for 1 … k m . Return
to step 3.




SOURCE CODE:
#include<stdio.h>
static int mark[20];
int i,j,np,nr;

int main()
{
int alloc[10][10],request[10][10],avail[10],r[10],w[10];

printf("\nEnter the no of process: ");
scanf("%d",&np);
printf("\nEnter the no of resources: ");
scanf("%d",&nr);
for(i=0;i<nr;i++)
{
printf("\nTotal Amount of the Resource R%d: ",i+1);
scanf("%d",&r[i]);
}




printf("\nEnter the request matrix:");

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&request[i][j]);

printf("\nEnter the allocation matrix:");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&alloc[i][j]);
/*Available Resource calculation*/
for(j=0;j<nr;j++)
{
avail[j]=r[j];
for(i=0;i<np;i++)
{
avail[j]-=alloc[i][j];

}
}

//marking processes with zero allocation

for(i=0;i<np;i++)
{
int count=0;
 for(j=0;j<nr;j++)
   {
      if(alloc[i][j]==0)
        count++;
      else
        break;
    }
 if(count==nr)
 mark[i]=1;
}
// initialize W with avail

for(j=0;j<nr;j++)
    w[j]=avail[j];

//mark processes with request less than or equal to W
for(i=0;i<np;i++)
{
int canbeprocessed=0;
 if(mark[i]!=1)
{
   for(j=0;j<nr;j++)
    {
      if(request[i][j]<=w[j])
        canbeprocessed=1;
      else
         {
         canbeprocessed=0;
         break;
          }
     }
if(canbeprocessed)
{
mark[i]=1;

for(j=0;j<nr;j++)
w[j]+=alloc[i][j];
}
}
}

//checking for unmarked processes
int deadlock=0;
for(i=0;i<np;i++)
if(mark[i]!=1)
deadlock=1;


if(deadlock)
printf("\n Deadlock detected");
else
printf("\n No Deadlock possible");
}


OUTPUT:

Enter the no of process: 4
Enter the no of resources: 5

Total Amount of the Resource R1: 2
Total Amount of the Resource R2: 1
Total Amount of the Resource R3: 1
Total Amount of the Resource R4: 2
Total Amount of the Resource R5: 1

Enter the request matrix:0 1 0 0 1
0 0 1 0 1
0 0 0 0 1
1 0 1 0 1

Enter the allocation matrix:1 0 1 1 0
1 1 0 0 0
0 0 0 1 0
0 0 0 0 0

 Deadlock detected
--------------------------------


Tuesday, 3 November 2015

Child parent process for sorting using fork() call - Operating Systems

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
int i,j;
int a[5];
printf("\nEnter 5 numbers:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
pid=fork();
if(pid==0)
{
for(i=0;i<4;i++)
for(j=i+1;j<5;j++)
{
if (a[i]>a[j])
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

for(i=0;i<5;i++)
printf("%d",a[i]);
}
}

Sunday, 1 November 2015

C program for simulation of Paging Technique Operating Systems

#include<stdio.h>
void main()
{
int memsize=15;
int pagesize,nofpage;
int p[100];
int frameno,offset;
int logadd,phyadd;
int i;
int choice=0;
printf("\nYour memsize is %d ",memsize);
printf("\nEnter page size:");
scanf("%d",&pagesize);

nofpage=memsize/pagesize;

for(i=0;i<nofpage;i++)
{
printf("\nEnter the frame of page%d:",i+1);
scanf("%d",&p[i]);
}

do
{
printf("\nEnter a logical address:");
scanf("%d",&logadd);
frameno=logadd/pagesize;
offset=logadd%pagesize;
phyadd=(p[frameno]*pagesize)+offset;
printf("\nPhysical address is:%d",phyadd);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
}

OUTPUT:
Your memsize is 15
Enter page size:5

Enter the frame of page1:2

Enter the frame of page2:4

Enter the frame of page3:7

Enter a logical address:3

Physical address is:13
Do you want to continue(1/0)?:1

Enter a logical address:1

Physical address is:11
Do you want to continue(1/0)?:0

Producer Consumer Problem - C Program - Operating Systems

#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>


sem_t prodlock;
sem_t conslock;
int product;


void *producer()
{
int i=1;
int item=1;
while(i<=5)
{
sem_wait(&prodlock);

product=item;
printf("\nProduced:%d",product);
sem_post(&conslock);
item++;
i++;

}
}

void *consumer()
{
int i=1;
while(i<=5)
{
sem_wait(&conslock);
printf("\nConsumed:%d",product);
sem_post(&prodlock);
i++;
}
}


void main()
{
pthread_t pid;
pthread_t cid;
pthread_attr_t *attr=NULL;
sem_init(&prodlock,0,1);
sem_init(&conslock,0,0);
if(pthread_create(&pid,attr,producer,NULL)!=0)
{
printf("\nError in creating Producer thread");
}
if(pthread_create(&cid,attr,consumer,NULL)!=0)
{
printf("\nError in creating Consumer thread");
}

pthread_join(pid,NULL);
pthread_join(cid,NULL);
}

OUTPUT:

Produced:1
Consumed:1
Produced:2
Consumed:2
Produced:3
Consumed:3
Produced:4
Consumed:4
Produced:5
Consumed:5

Priority Based CPU Scheduling - C Program - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,wt,tt,priority;
int processed;
float ntt;
}p[10];
int n;
void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}

void main()
{
int i,j,time=0,sum_bt=0,largest;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time , burst time, priority of process%c: ",p[i].name);
 scanf("%d%d%d",&p[i].at,&p[i].bt,&p[i].priority);
 p[i].processed=0;
 sum_bt+=p[i].bt;

}
sortByArrival();
p[9].priority=-9999;
printf("\nName\tArrival Time\tBurst Time\tPriority\t WT \t TT \t NTT");
  for(time=p[0].at;time<sum_bt;)
  {
    largest=9;
    for(i=0;i<n;i++)
    {
      if(p[i].at<=time && p[i].processed!=1 && p[i].priority>p[largest].priority)
        largest=i;
     }
      time+=p[largest].bt;
 p[largest].ct=time;
          p[largest].wt=p[largest].ct-p[largest].at-p[largest].bt;
     p[largest].tt=p[largest].ct-p[largest].at;
     p[largest].ntt=((float)p[largest].tt/p[largest].bt);
    p[largest].processed=1;
    avgwt+=p[largest].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t%d\t%d\t%f",p[largest].name,p[largest].at,p[largest].bt,p[largest].priority,p[largest].wt,p[largest].tt,p[largest].ntt);
}
printf("\nAverage waiting time:%f\n",avgwt/n);
}

OUTPUT:

Enter no of processes:5

Enter the arrival time , burst time, priority of processA: 0 3 2

Enter the arrival time , burst time, priority of processB: 2 6 3

Enter the arrival time , burst time, priority of processC: 4 4 1

Enter the arrival time , burst time, priority of processD: 6 5 4

Enter the arrival time , burst time, priority of processE: 8 2 2

Name    Arrival Time    Burst Time      Priority         WT      TT      NTT
A               0                            3               2                     0       3       1.000000
B               2                            6               3                     1       7       1.166667
D               6                            5               4                     3       8       1.600000
E               8                             2               2                    6       8       4.000000
C               4                             4               1                  12      16      4.000000
Average waiting time:4.400000


HRRN CPU Scheduling - C Program - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,wt,tt;
int completed;
float ntt;
}p[10];
int n;

void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
void main()
{
int i,j,time,sum_bt=0;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time and burst time of process%c: ",p[i].name);
 scanf("%d%d",&p[i].at,&p[i].bt);
 p[i].completed=0;
 sum_bt+=p[i].bt;

}
sortByArrival();

printf("\nName\tArrival Time\tBurst Time\tWaiting Time\tTurnAround Time\t Normalized TT");
  for(time=p[0].at;time<sum_bt;)
  {
 
   float hrr=-9999;
   int loc;
  for(i=0;i<n;i++)
  {
 
   if(p[i].at<=time && p[i].completed!=1)
            {
              float temp=(p[i].bt + (time-p[i].at))/p[i].bt;
              if(hrr < temp)
               {
                hrr=temp;
                loc=i;
               }
         
   }
   }
 
 
   time+=p[loc].bt;
   p[loc].wt=time-p[loc].at-p[loc].bt;
   p[loc].tt=time-p[loc].at;
   p[loc].ntt=((float)p[loc].tt/p[loc].bt);
   p[loc].completed=1;
   avgwt+=p[loc].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d\t\t%f",p[loc].name,p[loc].at,p[loc].bt,p[loc].wt,p[loc].tt,p[loc].ntt);
  }

printf("\nAverage waiting time:%f\n",avgwt/n);
}

OUTPUT:

Enter no of processes:5

Enter the arrival time and burst time of processA: 0 3

Enter the arrival time and burst time of processB: 2 6

Enter the arrival time and burst time of processC: 4 4

Enter the arrival time and burst time of processD: 6 5

Enter the arrival time and burst time of processE: 8 2

Name    Arrival Time    Burst Time      Waiting Time    TurnAround Time  Normalized TT
A               0                        3                             0               3                             1.000000
B               2                        6                             1               7                             1.166667
C               4                        4                             5               9                             2.250000
E               8                        2                             5               7                             3.500000
D               6                       5                              9               14                          2.800000
Average waiting time:4.000000



FCFS CPU Scheduling - C Program - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,tt;
float ntt;
}p[10];
int n;
void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}

void main()
{
int i,j,time=0;
char c;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time of process%d: ",i+1);
 scanf("%d",&p[i].at);
 printf("\nEnter the burst time of process%d: ",i+1);
 scanf("%d",&p[i].bt);
}

sortByArrival();

printf("\nName\tArrival Time\tBurst Time\tTurnAround Time\t  Normalized TT");

for(i=0;i<n;i++)
{
time+=p[i].bt;
p[i].ct=time;
p[i].tt=p[i].ct-p[i].at;
p[i].ntt=((float)p[i].tt/p[i].bt);
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%f",p[i].name,p[i].at,p[i].bt,p[i].tt,p[i].ntt);
}
}



OUTPUT:
Enter no of processes:5

Enter the arrival time of process1: 0

Enter the burst time of process1: 3

Enter the arrival time of process2: 2

Enter the burst time of process2: 6

Enter the arrival time of process3: 4

Enter the burst time of process3: 4

Enter the arrival time of process4: 6

Enter the burst time of process4: 5

Enter the arrival time of process5: 8

Enter the burst time of process5: 2

Name    Arrival Time    Burst Time      TurnAround Time   Normalized TT
A               0                                3               3               1.000000
B               2                                6               7               1.166667
C               4                                4               9               2.250000
D               6                               5               12              2.400000
E               8                                2               12              6.000000

Shortest Job First - CPU Scheduling - Operating Systems

#include<stdio.h>
struct process
{
char name;
int at,bt,ct,wt,tt;
int processed;
float ntt;
}p[10];
int n;

void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
void main()
{
int i,j,time,sum_bt=0,smallest;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time of process%c: ",p[i].name);
 scanf("%d",&p[i].at);
 printf("\nEnter the burst time of process%c: ",p[i].name);
 scanf("%d",&p[i].bt);
 p[i].processed=0;
 sum_bt+=p[i].bt;

}
sortByArrival();
p[9].bt=9999;
printf("\nName\tArrival Time\tBurst Time\tWaiting Time\tTurnAround Time\t Normalized TT");
  for(time=p[0].at;time<sum_bt;)
  {
    smallest=9;
    for(i=0;i<n;i++)
    {
      if(p[i].at<=time && p[i].processed!=1 && p[i].bt<p[smallest].bt)
        smallest=i;
    }
      time+=p[smallest].bt;
 p[smallest].ct=time;
          p[smallest].wt=time-p[smallest].at-p[smallest].bt;
     p[smallest].tt=p[smallest].wt+p[smallest].bt;
     p[smallest].ntt=((float)p[smallest].tt/p[smallest].bt);
    p[smallest].processed=1;
    avgwt+=p[smallest].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d\t\t%f",p[smallest].name,p[smallest].at,p[smallest].bt,p[smallest].wt,p[smallest].tt,p[smallest].ntt);
}
printf("\nAverage waiting time:%f\n",avgwt/n);
}




OUTPUT:


Enter no of processes:5

Enter the arrival time of processA: 0 3

Enter the arrival time of processB: 2 6

Enter the arrival time of processC: 4 4

Enter the arrival time of processD: 6 5

Enter the arrival time of processE: 8 2

Name    Arrival Time    Burst Time      Waiting Time    TurnAround Time  Normalized TT
A                0                            3                        0               3                   1.000000
B                2                            6                        1               7                   1.166667
E                8                            2                        1               3                   1.500000
C               4                            4                        7               11                  2.750000
D               6                            5                        9               14                  2.800000
Average waiting time:3.600000

Round Robin CPU Scheduling - C Program - Operating Systems

/* Round Robin algorithm for CPU scheduling ( considering arrival time  and maintains a queue
as well)
Ref. Operating Systems by william stallings */

#include<stdio.h>
struct process
{
char name;
int at,bt,wt,tt,rt;
int completed;
float ntt;
}p[10];
int n;
int q[100];  //queue
int front=-1,rear=-1;
void enqueue(int i)
{
if(rear==100)
{
printf("overflow");
return 0;
}rear++;
q[rear]=i;
if(front==-1)
front=0;

}

int dequeue()
{
if(front==-1)
{
printf("underflow");
return 0;
} int temp=q[front];
if(front==rear)
front=rear=-1;
else
front++;
return temp;
}
int isInQueue(int i)
{int k;
for(k=front;k<=rear;k++)
{
if(q[k]==i)
return 1;
}
return 0;

}void sortByArrival()
{
struct process temp;
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(p[i].at>p[j].at)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}

void main()
{
int i,j,time=0,sum_bt=0,tq;
char c;
        float avgwt=0;
 printf("Enter no of processes:");
 scanf("%d",&n);
 for(i=0,c='A';i<n;i++,c++)
 {
 p[i].name=c;
 printf("\nEnter the arrival time and burst time of process %c: ",p[i].name);
 scanf("%d%d",&p[i].at,&p[i].bt);
 p[i].rt=p[i].bt;
 p[i].completed=0;
 sum_bt+=p[i].bt;

}

printf("\nEnter the time quantum:");
scanf("%d",&tq);

sortByArrival();
enqueue(0);          // enqueue the first process
printf("Process execution order: ");
for(time=p[0].at;time<sum_bt;)       // run until the total burst time reached
{   i=dequeue();

if(p[i].rt<=tq)
{                          // for processes having remaining time with less than or equal time quantum
                     
time+=p[i].rt;
p[i].rt=0;
p[i].completed=1;        
   printf(" %c ",p[i].name);
            p[i].wt=time-p[i].at-p[i].bt;
            p[i].tt=time-p[i].at;    
            p[i].ntt=((float)p[i].tt/p[i].bt);
            for(j=0;j<n;j++)                // enqueue the processes which have come while scheduling
            {
            if(p[j].at<=time && p[j].completed!=1&& isInQueue(j)!=1)
            {
            enqueue(j);
           
            }
           }
        }
   else               // more than time quantum
   {
    time+=tq;
    p[i].rt-=tq;
    printf(" %c ",p[i].name);
    for(j=0;j<n;j++)             //enqueue the processes which have come scheduling first
            {
            if(p[j].at<=time && p[j].completed!=1&&i!=j&& isInQueue(j)!=1)
              {
            enqueue(j);
           
            }
           }
           enqueue(i);   // then enqueue the uncompleted process
         
   }

 
 
}

printf("\nName\tArrival Time\tBurst Time\tWaiting Time\tTurnAround Time\t Normalized TT");
for(i=0;i<n;i++)
{avgwt+=p[i].wt;
printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d\t\t%f",p[i].name,p[i].at,p[i].bt,p[i].wt,p[i].tt,p[i].ntt);
}
printf("\nAverage waiting time:%f\n",avgwt/n);
}


     


 OUTPUT:
Enter no of processes:5

Enter the arrival time and burst time of process A: 0 3

Enter the arrival time and burst time of process B: 2 6

Enter the arrival time and burst time of process C: 4 4

Enter the arrival time and burst time of process D: 6 5

Enter the arrival time and burst time of process E: 8 2

Enter the time quantum:4
Process execution order:  A  B  C  D  B  E  D
Name    Arrival Time    Burst Time      Waiting Time    TurnAround Time  Normalized TT
A               0                              3              0                           3                 1.000000
B               2                             6               9                           15                 2.500000
C               4                             4               3                            7                  1.750000
D               6                             5               9                          14                 2.800000
E               8                             2               9                           11                 5.500000
Average waiting time:6.000000

--------------------------------
Process exited after 16.79 seconds with return value 31
Press any key to continue . . .

C Program for Banker's Algorithm for deadlock avoidance - Operating Systems

#include<stdio.h>
static int visited[20];
int i,j,np,nr;



int canbeprocessed(int x[],int y[],int z[],int avail[])
{
for(j=0;j<nr;j++)
if(x[j]>avail[j])
return 0;
for(j=0;j<nr;j++)
{
avail[j]+=y[j];
y[j]=z[j]=0;
}
return 1;
}


int safe(int request[10][10],int avail[10],int alloc[10][10],int claim[10][10])
{
int count=0;
printf("\nSafe State Sequence: ");
while(count<np)
{
for(i=0;i<np;i++)
{
    if((visited[i]==0) && canbeprocessed(request[i],alloc[i],claim[i],avail))
    {
    count++;
    visited[i]=1;
    printf("P%d\t",i+1);
    break;        //if found break loop
    }
}
if(i==np) // all processes found to be not suitable for execution
return 0;
}
return 1;
}



int main()
{
int alloc[10][10],claim[10][10],request[10][10],avail[10],r[10];

printf("\nEnter the no of process: ");
scanf("%d",&np);
printf("\nEnter the no of resources: ");
scanf("%d",&nr);
for(i=0;i<nr;i++)
{
printf("\nTotal Amount of the Resource R%d: ",i+1);
scanf("%d",&r[i]);
}
printf("\nEnter the allocation matrix:");

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&alloc[i][j]);

printf("\nEnter the claim matrix:");

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&claim[i][j]);

for(i=0;i<np;i++)
for(j=0;j<nr;j++)
request[i][j]=claim[i][j]-alloc[i][j];
/*Available Resource calculation*/
for(j=0;j<nr;j++)
{
avail[j]=r[j];
for(i=0;i<np;i++)
{
avail[j]-=alloc[i][j];

}
}
/*Available Resource Calculation ends*/
if(safe(request,avail,alloc,claim))
printf("\n\nConclusion: System is in safe state ");
else
printf("\n\nConclusion: The system cannot acheive safe state" );
return 0;
}

Dining Philosopher Program in C - Operating Systems

 # include<stdio.h>
# include<pthread.h>
# include<semaphore.h>

sem_t fork[100];
int n;

void *phil_job(int no)
{
printf("\nPhilosopher %d is thinking",no+1);

sem_wait(&fork[no]);
sem_wait(&fork[(no+1)%n]);

printf("\nPhilosopher %d started eating",no+1);
sleep(1);
printf("\nPhilosopher %d finished eating",no+1);
sem_post(&fork[(no+1)%n]);
sem_post(&fork[no]);
}


void main()
{

int i;
pthread_t phil_thread[100];

printf("\nEnter the number of philosopher :");
scanf("%d",&n);

for(i=0;i<n;++i)
if(sem_init(&fork[i],0,1)==-1)
{
perror("semaphore initialization failed");
exit(1);
}

for(i=0;i<n;++i)
{
if(pthread_create(&phil_thread[i],NULL,phil_job,(int*) i)!=0)
{
perror("semaphore creation failed");
exit(1);
}

}



for(i=0;i<n;++i)
if(pthread_join(phil_thread[i],NULL)!=0)
{
perror("semaphore join failed");
exit(1);
}



printf("\n \n thread join succesfull\n");

for(i=0;i<n;++i)
if(sem_destroy(&fork[i])==-1)
{
perror("semaphore destruction failed");
exit(1);

}
}


OUTPUT:

Enter the number of philosopher :5

Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 1 started eating
Philosopher 4 is thinking
Philosopher 4 started eating
Philosopher 3 is thinking
Philosopher 5 is thinking
Philosopher 4 finished eating
Philosopher 1 finished eating
Philosopher 3 started eating
Philosopher 5 started eating
Philosopher 3 finished eating
Philosopher 2 started eating
Philosopher 5 finished eating
Philosopher 2 finished eating

 thread join succesfull



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



Simulation of Page replacement algorithms in C - Operating Systems

This is a single c program which covers the 5 important page replacement algorithms in virtual memory chapter of operating system.
1.FIFO
2.Optimal
3.LRU
4.LFU
5.Second chance

SOURCE CODE:
#include<stdio.h>
int n,nf;
int in[100];
int p[50];
int hit=0;
int i,j,k;
int pgfaultcnt=0;
int bn;

void getData()
{
printf("\nEnter length of page reference sequence:");
scanf("%d",&n);
printf("\nEnter the page reference sequence:");
for(i=0;i<n;i++)
scanf("%d",&in[i]);
printf("\nEnter no of frames:");
scanf("%d",&nf);
}

void initialize()
{
pgfaultcnt=0;
bn=0;
for(i=0;i<nf;i++)
p[i]=9999;              // 9999 is used to represent empty frame
}

//function to check whether page fault occurs or not
int isHit(int data)
{
hit=0;
   for(j=0;j<nf;j++)
     {
       if(p[j]==data)
         {
          hit=1;
          break;
         }
     
     }

return hit;            
}

//function which returns the index of the page which is set
int getHitIndex(int data)
{
int hitind;
for(k=0;k<nf;k++)
{
if(p[k]==data)
{
hitind=k;
break;
}
}
return hitind;
}

void dispPages()
{
for (k=0;k<nf;k++)
{
if(p[k]!=9999)      //display except 9999
printf(" %d",p[k]);
}

}

void dispPgFaultCnt(){
printf("\nTotal no of page faults:%d",pgfaultcnt);
}

void fifo()
{
initialize();

for(i=0;i<n;i++)
{
printf("\nFor %d :",in[i]);

if(isHit(in[i])==0)
{
  p[bn]=in[i];          
  bn++;
  pgfaultcnt++;
  dispPages();
  if(bn==nf)                      // to treat as a circular queue
  bn=0;
}
else
printf("No page fault");
}
dispPgFaultCnt();
}




void optimal()
{
initialize();
int near[50];

for(i=0;i<n;i++)
{
printf("\nFor %d :",in[i]);

    if(isHit(in[i])==0)
    {
       pgfaultcnt++;
           if(bn<nf)                          // there are spaces to insert new pages
              {
                p[bn]=in[i];
                 bn++;
              }
           else                                // any page must be replaced
              {          
               for(j=0;j<nf;j++)
                 {  
                   int pg=p[j];
                   int found=0;
                   for(k=i;k<n;k++)
                   {
         
                     if(pg==in[k])
                    {
                      near[j]=k;
                      found=1;
                      break;
                    }
         
                  }
              if(!found)
              near[j]=9999;
                }
            int max=-9999;
            int repindex;
             for(j=0;j<nf;j++)
             {
               if(near[j]>max)          
              {
               max=near[j];
               repindex=j;
              }
             }
            p[repindex]=in[i];
         }

dispPages();
   }
else
printf("No page fault");
}
dispPgFaultCnt();
}

void lru()
{
initialize();

int least[50];
for(i=0;i<n;i++)
{

printf("\nFor %d :",in[i]);

if(isHit(in[i])==0)
{

for(j=0;j<nf;j++)
       {
         int pg=p[j];
         int found=0;
        for(k=i-1;k>=0;k--)
         {
           if(pg==in[k])
            {
             least[j]=k;
             found=1;
             break;
            }
         
         }
        if(!found)
          least[j]=-9999;
       }
  int min=9999;
  int repindex;
for(j=0;j<nf;j++)
{
if(least[j]<min)
  {
    min=least[j];
    repindex=j;
  }
}
p[repindex]=in[i];
pgfaultcnt++;

dispPages();
}
else
printf("No page fault!");
}
dispPgFaultCnt();
}

void lfu()
{
int usedcnt[100];
int least,repin,sofarcnt=0;
initialize();
for(i=0;i<nf;i++)
usedcnt[i]=0;

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

printf("\n For %d :",in[i]);
if(isHit(in[i]))
{
int hitind=getHitIndex(in[i]);
usedcnt[hitind]++;
printf("No page fault!");
}
else
{
pgfaultcnt++;
          if(bn<nf)
           { p[bn]=in[i];
             usedcnt[bn]++;
             bn++;
           }
          else
          { least=9999;
             for(k=0;k<nf;k++)
                 if(usedcnt[k]<least)
                  { least=usedcnt[k]; repin=k; }
            p[repin]=in[i];
            sofarcnt=0;
            for(k=0;k<=i;k++)
            if(in[i]==in[k])
            sofarcnt++;
            usedcnt[repin]=sofarcnt;
          }

 dispPages();
}



}
dispPgFaultCnt();
}

void secondchance()
{
int usedbit[50];
int victimptr=0;
initialize();
for(i=0;i<nf;i++)
usedbit[i]=0;
for(i=0;i<n;i++)
{
printf("\nFor %d:",in[i]);
 if(isHit(in[i]))
{
    printf("No page fault!");
     int hitindex=getHitIndex(in[i]);
     if(usedbit[hitindex]==0)
        usedbit[hitindex]=1;
}
else
{
      pgfaultcnt++;
      if(usedbit[victimptr]==1)
        {
          do
           {
            usedbit[victimptr]=0;
            victimptr++;
             if(victimptr==nf)
              victimptr=0;
           }while(usedbit[victimptr]!=0);
        }
     if(usedbit[victimptr]==0)
      {
       p[victimptr]=in[i];
       usedbit[victimptr]=1;
       victimptr++;
      }
     dispPages();
 
}
if(victimptr==nf)
victimptr=0;
}
dispPgFaultCnt();
}
       



int main()
{
int choice;
while(1)
{
printf("\nPage Replacement Algorithms\n1.Enter data\n2.FIFO\n3.Optimal\n4.LRU\n5.LFU\n6.Second Chance\n7.Exit\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
    getData();
    break;
case 2:
     fifo();
     break;
case 3:
    optimal();
    break;
case 4:
    lru();
    break;
case 5:
    lfu();
    break;
case 6:
    secondchance();
    break;
default:
    return 0;
    break;
}
}
}