Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

Tuesday, August 7, 2012

LRU Page replacement Algorithm

Below is a C Program Which Explains the LRU Page replacement Algorithm in a Proper and Clear Way.

#include<stdio.h>
#include<conio.h>
struct node
{
  int pno,reftime;
}frames[20];
int n;

int page_found(int pno)
{
  int fno;
  for(fno=0;fno<n;fno++)
    if(frames[fno].pno==pno)
       return fno;
    return -1;
}

int get_free_frame()
{  int fno;
  for (fno=0; fno<=n; fno++)
    if (frames[fno].pno==-1)
        return(fno);
   return(-1);
}

int get_lru_frame()
{
  int fno;
  int selfno=0;
  for (fno=1; fno<n; fno++)
    if(frames[fno].reftime<frames[selfno].reftime)
    selfno=fno;
  return selfno;
}
void main()
{
   int p_request[]={5,8,10,14,10,9,5,10,8,5,1,10,9,12,10};
   int size=15,currtime;
   int page_falts=0,i,j,fno;
   clrscr();
   printf("\nHow many frames:");  scanf("%d",&n);
   //initialize frames
   for (i=0; i<n; i++)
   { frames[i].pno=-1;
     frames[i].reftime=-1;
   }

   printf("\nPageNo     Page Frames          Page Fault");
   printf("\n-------------------------------------------");
   currtime=0;
   for(i=0;i<size;i++)
   {
     j=page_found(p_request[i]);
     if(j==-1)  //page fault occurs
     {
       j=get_free_frame();
       if (j==-1) //no free frame - do page replacement
         j=get_lru_frame();
       page_falts++;
       frames[j].pno=p_request[i];
       frames[j].reftime=currtime;
       printf("\n%4d\t ",p_request[i]);
       for (fno=0; fno<n; fno++)
         printf("%4d",frames[fno].pno);
       printf(" : YES");
     }
    else//page found
    {
       printf("\n%4d\t ",p_request[i]);
       frames[j].reftime=currtime;
       for (fno=0; fno<n; fno++)
         printf("%4d",frames[fno].pno);
       printf(" : NO");
    }
       currtime++;
   }
  printf("\n------------------------------------------");
  printf("\n Number of Page_Falts=%d",page_falts);
  getch();
}

MFU Page Replacement Algorithm

Here is a C Program Which Explain the Working of MFU Page Replacement Algorithm in C.

#include<stdio.h>
#include<conio.h>
struct node
{
  int pno,freq;
}frames[20];
int n;

int page_found(int pno)
{
  int fno;
  for(fno=0;fno<n;fno++)
    if(frames[fno].pno==pno)
       return fno;
    return -1;
}

int get_free_frame()
{  int fno;
  for (fno=0; fno<=n; fno++)
    if (frames[fno].pno==-1)
        return(fno);
   return(-1);
}

int get_mfu_frame()
{
  int fno;
  int selfno=0;
  for (fno=1; fno<n; fno++)
    if(frames[fno].freq>frames[selfno].freq)
    selfno=fno;
  return selfno;
}
void main()
{
   int p_request[]={5,8,10,14,10,9,5,10,8,5,1,10,9,12,10};
   int size=15;
   int page_falts=0,i,j,fno;
   clrscr();
   printf("\nHow many frames:");  scanf("%d",&n);
   //initialize frames
   for (i=0; i<n; i++)
   { frames[i].pno=-1;
     frames[i].freq=0;
   }

   printf("\nPageNo     Page Frames              Page Fault");
   printf("\n---------------------------------------------------");
   for(i=0;i<size;i++)
   {
     j=page_found(p_request[i]);
     if(j==-1)  //page fault occurs
     {
       j=get_free_frame();
       if (j==-1) //no free frame - do page replacement
         j=get_mfu_frame();
       page_falts++;
       frames[j].pno=p_request[i];
       frames[j].freq=1;
       printf("\n%4d\t ",p_request[i]);
       for (fno=0; fno<n; fno++)
         printf("%4d:%2d",frames[fno].pno,frames[fno].freq);
       printf(" : YES");
     }
    else //page found in frame j
    {
       printf("\n%4d\t ",p_request[i]);
       frames[j].freq++;
       for (fno=0; fno<n; fno++)
         printf("%4d:%2d",frames[fno].pno,frames[fno].freq);
       printf(" : NO");
    }
   }
  printf("\n-------------------------------------------------------");
  printf("\n Number of Page_Falts=%d",page_falts);
  getch();
}

C Program To Print Lines From File

Below Given Is a Simple Program which prints the lines of a file but with different user given instructions.

The Feature of the Program is as Follows:

The Program Prints,

1) print first 10 lines of file

2) print last  20 lines of file

3) print all lines of file


#include <stdio.h>
#include <conio.h>
#include <process.h>
void main(int argc, char *argv[])
{
    int tot_lines,cnt;
    char *ptr;
    if( argc != 3 )
    {
        printf("\nInvalid number of arguments\n");
        return;
    }
    if( *argv[1] == '+' || *argv[1] == '-')
    {
        tot_lines = count_lines(argv[2]);
        ptr = argv[1];
        ptr++;  // skip '+' or '-'
        cnt = atoi(ptr);
        if ( cnt > tot_lines)
        {
            printf("\nInvalid line count\n");
            return;
        }
    }
    if( *argv[1] == '+' ) // typeline +cnt fname
        print_top_lines(argv[2],cnt);
    else
    if( *argv[1] == '-' ) // typeline -cnt fname
        print_bottom_lines(argv[2],cnt,tot_lines);
    else if (*argv[1]=='a')
        print_all_lines(argv[2]);
     else
         printf("\nInvalid option...");
} // main

int count_lines( char *fname)
{
    int tot_lines,ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open file");
        return(-1);
    }
    tot_lines = 0;
    while (fgets(buff,80,fp)!=NULL)
       tot_lines++;
    tot_lines++;
    fclose(fp);
    return(tot_lines);
} // count lines


int print_all_lines( char *fname)
{
    int ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    printf("\n");
    while(fgets(buff,80,fp)!=NULL)
     printf("%s",buff);

    fclose(fp);
    return;
} // print all lines

int print_top_lines(char *fname, int cnt)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];

    curr_cnt = 0;

    fp = fopen(fname,"r");

    fgets(buff,80,fp);
    printf("\n");
    while( curr_cnt < cnt )
    {
        printf("%s",buff);
        fgets(buff,80,fp);
        curr_cnt++;
    }
    fclose(fp);
    return;
}
int print_bottom_lines(char *fname, int cnt, int tot_lines)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];
    curr_cnt = 0;
    printf("\n");
    fp = fopen(fname,"r");
    while( 1)
    {
        fgets(buff,80,fp);
        curr_cnt++;
        if( curr_cnt >= tot_lines - cnt )
            break;
    }
    while( fgets(buff,80,fp) != NULL)
    {
        printf("%s", buff);
    }
    fclose(fp);
    return;
}

Shell Program For Searching a String.

Below is a Simple Shell Program in C Language which Implement search command as follows

1) search first occurrence of pattern in file name

2) count no of occurrences of pattern in file name

3) search all occurrences of pattern in file name


#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <string.h>


void main( int argc, char *argv[])
{
    char pattern[20],fname[20],option;

    printf("\nSearch Starts..");
    if( argc != 4 )
    {
        printf("\nInvalid number of arguments");
        return;
    }// if
    // set param
    option = *argv[1];
    strcpy(pattern,argv[2]);
    strcpy(fname,argv[3]);

    switch(option)
    {
        case 'f' :       find_first_occ(fname,pattern);
                        break;
        case 'c' :       count_all_occ(fname,pattern);
                        break;
        case 'a' :       print_all_occ(fname,pattern);
                        break;
        default  :        printf("\nInvalid option");
                        break;
    } // switch
} // main

int find_first_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr;
    int i,m,c,lineno;

    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    lineno=0;
    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);
        lineno++;

        ptr = strstr(str,pattern);
        if( ptr != NULL )
        {
            printf("\n lineno = %d : Line = %s", lineno,str);
            printf("\n position = %d", ptr - str +1 );
            break;
        }
    } // while
    fclose(fp);
    return;
} // find first occ


int count_all_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr,*ptr1;
    int count=0;

    int i,m,c,lineno;

    fp = fopen(fname,"r");

    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);

        ptr1 = str;
        ptr = strstr(ptr1,pattern);

        while( ptr != NULL )
        {
            count++;
            ptr1= ptr+1;
            ptr = strstr(ptr1,pattern);
        }
    } // while
    fclose(fp);
    printf("\nPattern %s occurs %d times", pattern,count);
    return;
} // count all occ


int print_all_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr,*ptr1;
    int lineno=0;

    int i,m,c;

    fp = fopen(fname,"r");

    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);
        lineno++;
        if( strstr(str,pattern) != NULL )
            printf("Line:%d: %s",lineno,str);

    } // while
    fclose(fp);
    return;
} // print all occurences

LOOK Algorithm using Disk Scheduling

Below is a Simple Program in C Language Which Explains Simulation of LOOK Algorithm of Disk Scheduling

#include <alloc.h>

struct reqblock
{ int block;
   struct reqblock *next;
} *first,*curr,*prev;

int n,currpos,headmove=0;
char direction;

void get_req_blocks();
 void scan();
void main()
{
  clrscr();
   printf("\nEnter total number of blocks in the disk:");
   scanf("%d",&n);
   printf("\nEnter request block numbers string terminated by -1\n");
    get_req_blocks();
    //print req string
    curr=first;
    while(curr!=NULL)
    { printf("%d\t",curr->block);
      curr=curr->next;
     }
     printf("\nEnter direction of head movement:(F-Forwad,B-Backward):");
     flushall(); scanf("%c",&direction);
      printf("\nEnter block no. as current head position:");
      scanf("%d",&currpos);
     scan();
     printf("\nNumber of headmovements:%d",headmove);
  }

  void get_req_blocks()
  { struct reqblock *t,*pt;
    int blockno;
    first=NULL;
    scanf("%d",&blockno);
    while(blockno!=-1)
    { curr=(struct reqblock *) malloc(sizeof(struct reqblock));
      curr->block=blockno;
      curr->next=NULL;
     if (first==NULL) //req str is empty
         first=curr;
     else
         prev->next=curr;
      prev=curr;
      scanf("%d",&blockno);
    }//while
  }

 void scan()
  {  int selblock;
     printf("\nList of request served:\n");

     while(first!=NULL)
     {
       if (!look())
         direction=(direction=='F')?'B':'F';
       selblock=get_next_block();
       if (selblock!=-1)
           printf("%d\t",selblock);
        if (direction=='F')
        {  if (currpos==n-1)
             direction='B';
         else
         {  currpos++; headmove++;
          }
      }
      else
      {
         if (currpos==0)
             direction='F';
         else
         { currpos--;  headmove++;}
       }
      }//while
      headmove--;
   }

 int look()
 {
   if (direction=='F')
   {  curr=first;
      while(curr!=NULL)
      {   if (curr->block>currpos)
          return(1);
          curr=curr->next;
       }
       return(0);
     }
   else //direction='B'
   {   curr=first;
      while(curr!=NULL)
      {  if (curr->block<currpos)
          return(1);
          curr=curr->next;
       }
       return(0);
     }
 }

 get_next_block()
   {
        int selblock;
         curr=first;
          while(curr->block!=currpos)
           {  prev=curr;
              curr=curr->next;
              if (curr==NULL) return(-1);
            }
            selblock=curr->block;
            if (curr==first)
               first=first->next;
             else
               prev->next=curr->next;
             free(curr);
            return(selblock);
  }

FIFO using Paging and Page Faults in C

Below is a Simple C Language Program Which shows simulation of demand paging & show page faults
  according to FIFO replacement


#include<stdio.h>
#include<conio.h>
int frames[]={-1,-1,-1};
int page_found(int pno)
{
 int i;
 for(i=0;i<3;i++)
 if(frames[i]==pno)
   return i;
 return -1;
}
void main()
{
 int i;
 int page_fault;
 int p_request[]={9,14,10,11,15,9,11,9,15,10,9,15,10,12,5};
 int size=15,page_faults=0;
 clrscr();
 printf("\n Page No.___Page_Frames");
 printf("\n_________________________\n");
 for(i=0;i<size;i++)
 {
  if(page_found(p_request[i]==-1))//next page is not in frame
  {
   frames[page_fault%3]=p_request[i];
   page_faults++;
   printf("%4d___%4d%4d%4d\n",p_request[i],frames[0],frames[1],frames[2]);
  }
  else
  printf("\n %4d",p_request[i]);
 }
 printf("\n_________________________\n");
 printf("\n Total Page Faults=%d",page_faults);
 getch();
}

Shell Program In C

Here is a Simple Shell Program In C Language which counts the number of  chars, words, and Lines Provided in the input.

#include <stdio.h>
#include <conio.h>

void count();

void main(int argc, char *argv[])
{
    char fname[20];
    char option;

    if( argc != 3 )
    {
        printf("Invalid number of arguments");
        return ;
    }
    option = *argv[1];
    strcpy(fname,argv[2]);
    count(fname, option);
} // main

void count( char fname[], char option)

{
    long ccnt, wcnt,lcnt;
    FILE  *fp;

    long lflag,wflag;
    int ch;

    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open a file");
        exit(0);
    }
    ccnt = wcnt = lcnt = 0;
    lflag = wflag = 1;
    ch = fgetc(fp);
    while( ch != EOF )
    {
        ccnt++;
        if( ch == ' ' || ch == '\t')
        {
            lflag = 0;
            if( wflag == 0 )
            {
                wcnt++;
                wflag = 1;
            }
        }
        else
        if( ch == 10 )
        {
            ccnt++;
            lcnt++;
            lflag = 1;
            if( wflag == 0 )
            {
                wcnt++;
                wflag = 1;
            }
        }
        else   // normal
        {
            wflag = 0;
            lflag = 0;
        }
        ch = fgetc(fp);
    } // while

    if( wflag == 0 )
        wcnt++;
    if( lflag == 0 )
        lcnt++;
    switch(option)
    {
        case 'c' :printf("\n char  count  = %ld\n",ccnt);
                  break;
        case 'w' :
                    printf("\n word  count  = %ld\n",wcnt);
                    break;
        case 'l' :
                    printf("\n line  count  = %ld\n",lcnt);
    } // switch
} // count

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...