SlideShare a Scribd company logo
1 of 30
Simulate all Page Replacement Algorithms

    a) FIFO Page Replacement Algorithm

#include<stdio.h>
#include<conio.h>
int str[30],z,count,fs,p[100],pf=0;
main()
{
 int i,j,k,temp;
 printf("n Enter the No.of frames:");
 scanf("%d",&fs);
 printf("n Enter string (-1 to stop):");
 i=0;
 while(1)
 {
  scanf("%d",&temp);
  if(temp==-1)
  break;
  str[i++]=temp;
 }
 count=i;
 for(i=0;i<fs;i++)
   p[i]=-1;
 printf("nt Pages t Frames");
 i=j=0;
 while(i<count)
 {
 if(!check(str[i]))
 {
  pf++;
  p[j]=str[i];
  j=(j+1)%fs;
 }
 printf("nt <%d> t",str[i]);
 for(k=0;k<fs;k++)
 if(p[k]!=-1)
  printf("%3d",p[k]);
 i++;
 }
 z=pf-fs;
 printf("nt Page Faults:%d",z);
 }
 check(int key)
 {
  int i;
  for(i=0;i<fs;i++)
  if(key==p[i])
  return 1;
return 0;
 }




OUTPUT:
1) Enter the No.of frames:3
 Enter string (-1 to stop):2 3 2 1 5 2 4 5 3 2 5 2 -1
    Pages Frames
      <2>      2
      <3>      2 3
      <2>      2 3
      <1>      2 3 1
      <5>      5 3 1
      <2>      5 2 1
      <4>      5 2 4
      <5>      5 2 4
      <3>      3 2 4
      <2>      3 2 4
      <5>      3 5 4
      <2>      3 5 2
      Page Faults:6
b) LRU Page Replacement Algorithm

#include<stdio.h>
#include<conio.h>
int str[30],count,fs,p[100],pf;
main()
{
 int i,j,k,z,temp;
 printf("n Enter the No.of frames:");
 scanf("%d",&fs);
 printf("n Enter string (-1 to stop):");
 i=0;
 while(1)
 {
 scanf("%d",&temp);
 if(temp==-1)
 break;
 str[i++]=temp;
 }
 count=i;
 for(i=0;i<fs;i++)
 p[i]=-1;
 printf("n Pages tt Frames");
 i=0;
 while(i<count)
 {
 if(!check(str[i]))
 {
  pf++;
  j=lru(i);
  p[j]=str[i];
 }
 printf("n %3d tt",str[i]);
 for(k=0;k<fs;k++)
 if(p[k]!=-1)
printf("%3d",p[k]);
 i++;
 }
 z=pf-fs;
 printf("nn Page Faults:%d",z);
 }
 check(int key)
 {
 int i;
 for(i=0;i<fs;i++)
 if(key==p[i])
 return 1;
 return 0;
}
lru(int pos)
{
int i,j=0,r=0;
for(i=0;i<fs;i++)
{
if(p[i]==-1)
return i;
if(rec(i,pos)>=r)
{
 j=i;
 r=rec(i,pos);
} }
return j;
}
rec(int fn,int pn)
{
int i,c=0;
for(i=pn-1;i>=0;i--)
{
 c++;
 if(p[fn]==str[i])
  return c;
 }
 }




OUTPUT
1) Enter the No. of frames: 3
Enter string (-1 to stop):2 3 2 1 5 2 4 5 3 2 5 2 -1
Pages         Frames
 2          2
 3          2 3
 2          2 3
 1          2 3 1
 5          2 5 1
 2          2 5 1
 4          2 5 4
 5          2 5 4
 3          3 5 4
 2          3 5 2
 5          3 5 2
 2          3 5 2

Page Faults:4
c) LFU page replacement Algorithm

#include<stdio.h>
int i,j=1,s,k,l,re[30],p[10],ch,no,nr,c,a1=0,a,line=6,nk;
struct
{
         int st,l,ps,pos;
}opr;
main()
{
         clrscr();
         printf("Enter length of reference string:");
         scanf("%d",&nr);
         printf(" Enter reference string:");
         for(i=1;i<=nr;i++)
         scanf("%d",&re[i]);
         printf("n Enter number of frames:");
         scanf("%d",&no);
         clrscr();
         for(i=1;i<=no;i++)
         p[i]=-1;
         opr.st=100;
         for(i=1;i<=nr;i++)
         {
                  a1=0;
                  opr.st=100;
                  opr.pos=100;
                  for(c=1;c<=no;c++)
                  if(re[i]==p[c])
                  a1++;
                  if(a1==0)
                  {
                           if(j<=no)
                           {
                                  p[j]=re[i];
                                  j++;
                           }
                           else
                           {
                                  for(k=1;k<=no;k++)
                                  {
                                          a=0;
                                          for(ch=i-1;ch>0;ch--)
                                          {
                                                 if(p[k]==re[ch])
                                                 {
                                                         a++;
                                                         nk=ch;
                                                 }
}
                                       if(a>1)
                                       {
                                                 if(opr.st>a)
                                                 {
                                                         opr.st=a;
                                                         opr.ps=k;
                                                 }
                                                 else
                                                 if(opr.st==a)
                                                 {
                                                         if(opr.pos>ch)
                                                         opr.ps=k;
                                                 }
                                       }
                                       else
                                       if(a==1)
                                       {
                                              if(opr.pos>nk)
                                              {
                                                      opr.pos=nk;
                                                      opr.ps=k;
                                                      opr.st=a;
                                              }
                                       }
                              }
                              p[(opr.ps)]=re[i];
                      }
               }
               display(no,p,i);
       }
       printf("n");
       getch();
}
display(int no,int p[],int i)
{
       int k;
       if(i==1)
       {
                printf("ttt");
                for(k=1;k<=no;k++)
                printf("_ _");
       }
       printf("n%d",re[i]);
       gotoxy(25,line++);
       for(k=1;k<=no;k++)
       {                printf("|");
                printf("_");
                if(p[k]!=-1)
printf("%d",p[k]);
              else
              printf(" ");
              printf("_");
       }      printf("|"); }




OUTPUT:

Least frequently used

Enter no of frame 3

Enter no of pages 4

Enter page sequence 4 5    8

400F

450F

458F

No of page faults 3
3.Simulate all File Allocation Strategies

a) Sequential file allocation

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct
{
        int bno,flag;
}block;
        block b[200];
void main()
{
        int rnum();


       int n,p[30],i,j,r,k[20][20],s,s1;
       printf("n input");



       printf("n enter no of files");
       scanf("%d",&n);
       printf("n-------------------------------");
       printf("n enter memory requirements");
       printf("n------------------------------");
       for(i=1;i<=n;i++)
       {
          printf("n enter %d file requirements:",i);
          scanf("%d",&p[i]);
       }
       for(i=1;i<=n;i++)
       {
          s1=rnum();
          j=0;
          for(s=s1;s<(s1+p[i]);s++)
          {
               j=j+1;
               b[s].bno=s;
               b[s].flag=1;
               k[i][j]=s;
          }
       }
       printf("n output");
       printf("n ---------------------------------");
       printf("n program blocka allocated");
       printf("n----------------------------------");
       for(i=1;i<=n;i++)
{
            printf("%5dt",i);
            for(j=1;j<=p[i];j++)
                 printf("%5d",k[i][j]);
            printf("'n");
        }
        printf("n------------------------------------");

printf("n allocated blocks:");
        printf("n-----------------------------------");
        for(i=1;i<=200;i++)
                if(b[i].flag==1)
                         printf("%5dt",b[i].bno);
}
int rnum()
{
        int i,k=0;
        for(i=1;i<=200;i++)
        {
                k=rand()%200;
                if(k%2==0)
                  k=k+10;
                if(b[k].flag!=1)
                  break;
                return k;
        }
}




OUTPUT:

Enter the no of input files : 3
Input the requirements:
Enter the no of blocks needed in file 1: 2
Enter the no of blocks needed in file2 :4
Enter the no of blocks needed in file3: 3
Allocation
Allocate for file1: 8386
Allocate for file2: 77159335
Allocate for file3:924921
b) Indexed File allocation

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct block
{
  int bno,flag;
};
struct block b[100];
int rnum();

void main()
{
   int p[10],r[10][10],ab[10],i,j,n,s;
    printf("n INPUT");
    printf("enter no of files:");
    scanf("%d",&n);
     for(i=1;i<=n;i++)
      {
         printf("n enter the size of block %d:",i);
         scanf("%d",&p[i]);
          }
  for(i=1;i<=n;i++)
  {
     s=rnum();
    ab[i]=s;
    for(j=0;j<p[i];j++)
    {
       s=rnum();
        r[i][j]=s;
    }
}
printf("n output:");
 for(i=1;i<=n;i++)
{
   printf("n file %d n block %d contains:",i,ab[i]);
   for(j=0;j<p[i];j++)
   {
      printf("%6d",r[i][j]);
    }
}
}
int rnum()
{
int k=0,i;
 for(i=1;i<=100;i++)
 {
k=rand()%100;
     if(b[k].flag!=-1)


       break;
  }
return k;
}




OUTPUT:

Enter the no of files: 3
Enter the memory requirements:

Enter the 1 file requirement: 3
Enter the 2 file requirement: 2
Enter the 3 file requirement: 4

Program blocks allocated
1      70     71     72
2      115    116
3      212    213    214    215
Allocated blocks
70 71 72 115 116 212 213 214 215
c) Linked File Allocation

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct
{
        int bno,flag,bn[20];
}block;
        block b[100],b1;
void main()
{
        int rnum();
        int p[30],kk[20],i,n,t,s1,s,r,j,c=1;
        printf("n enter no of i/p files");
        scanf("%d",&n);
        printf("n input the requirements");
        for(i=1;i<=n;i++)
        {
                printf("n enter the no of blocks needed for file%d",i);
                scanf("%d",&p[i]);
        }
        t=1;
        for(i=1;i<=n;i++)
        {
           for(j=1;j<=p[i];j++)
           {
                s=rnum();
                b[s].flag=1;
                b[c].bno=s;
                r=p[i]-1;
                kk[i]=s;
                t=1;
                c++;
            }
        }
        while(r!=0)
        {
                s1=rnum();
                b[s].bn[t]=s1;
                b[s1].flag=1;
                b[c].bno=s1;
                r=r-1;
                t=t+1;
                c++;
        }
        printf("n allocation:n");
c=1;
       for(i=1;i<=n;i++)
       {
         printf("n allocated for file%d",i);
         for(j=1;j<=p[i];j++)
         {
               if(j==1)
               {
                  printf("%3d",b[c].bno);
                  c++;
               }
               else
               {
                  printf("---->%3d",b[c].bno);
                  c++;
               }
          }
          printf("n");
       }
}
int rnum()
{
       int k=0,i;
       for(i=1;i<=100;i++)
       {
               k=rand()%100;
               if(b[k].flag!=1)
               break;
       }
       return k;
}


OUTPUT:

Enter the no of files 3
Enter the size of block 1 2 3
4 3 2
File 1 Block 83 contains 86 77 15 93
File 2 Block 85 contains 86 92 49
File 3 Block 21 contains 62 27
4. Simulate all File Organization Techniques

a) Single level directory
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
void main()
{
       int gd,gm,count,i,j,mid,cir_x;
       char fname[10][20];
       gd=DETECT;
       clrscr();
       initgraph(&gd,&gm,"c:/turboc");
       cleardevice();
       setbkcolor(GREEN);
       puts("n Enterno.of files do u have?");
       scanf("%d",&count);
       for(i=0;i<count;i++)
       {
               cleardevice();
               setbkcolor(GREEN);
               printf("Enter file %d name ",i+1);
               scanf("%s",fname[i]);
               setfillstyle(1,MAGENTA);
               mid=640/count;
               cir_x=mid/3;
               bar3d(270,100,370,150,0,0);
               settextstyle(2,0,4);
               settextjustify(1,1);
               outtextxy(320,125,"Root Directory");
               setcolor(BLUE);
               for(j=0;j<=i;j++,cir_x+=mid)
               {
                        line(320,150,cir_x,250);
                        fillellipse(cir_x,250,30,30);
                        outtextxy(cir_x,250,fname[i]);
               }
               getch();
       }
}
OUTPUT:
b) Two level Directory

//two level directory structure
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#define SX 250
#define SY 200
#define BL 30
#define BW 15
#define SY1 250
int SX1=100;
int n,m[10];
char a[10][10];
int cols[]={2,5,1,3,4,6,8,7,9};
typedef struct
{
 char name[10];
 struct
 {
  char file[10];
 }k[10];
}file_info;
file_info f[10];
void readfiles()
{
 int i,j;
 printf("nEnter no. of directories:");
 scanf("%d",&n);
 for(i=0;i<n;i++)
 {
  printf("Enter %d directory:",i+1);
  scanf("%s",&f[i].name);
  printf("enter no.of files:");
  scanf("%d",&m[i]);
  for(j=0;j<m[i];j++)
  {
   printf("enter %d file name:",j+1);
   scanf("%s",&f[i].k[j].file);
  }
 }
}
void fillspace()
{
 int x1,y1,i,j;
 outtextxy(70,205,"Directory");
 outtextxy(100,255,"Files");
 for(i=0;i<n;i++)
 {
setfillstyle(1,cols[i]);
  x1=SX+(i%10)*50;
  y1=SY+(i/10)*40;
  bar(x1,y1,x1+BL+20,y1+BW);
  outtextxy(x1+BL/4,y1+BW/4,f[i].name);
  line(x1+BL/2,y1+BW,SX1+50,SY1);
  SX1=SX1+50;
  for(j=0;j<m[i];j++)
  { setfillstyle(1,cols[i]);
  x1=SX1+(j%10)*40;
  y1=SY1+(j/10)*40;
  bar(x1,y1,x1+BL+10,y1+BW);
  outtextxy(x1+BL/4,y1+BW/4,f[i].k[j].file);
  line(x1+BL/2,y1+BW,x1+BL/2,y1+50);
  circle(x1+BL/2,y1+60,7);
  }
  SX1=SX1+100;
 }
}
void main()
{
 int gm,gd=DETECT;
 initgraph(&gd,&gm,"c:tcbgi");
 readfiles();
 cleardevice();
 getch();
 fillspace();
 getch();
 closegraph();
}
5.Interprocess Communication

   a) Pipes

#include<stdio.h>
 #include<string.h>
 #include<stdlib.h>
 #include<error.h>
 #define MAXBUFF 1024
 main()
 {
 int childpid,pipe1[2],pipe2[2];
 if(pipe(pipe1)<0||pipe(pipe2)<0)
 printf("error");
 if((childpid=fork())<0)
  {
 printf("error");
 }
 else if(childpid>0)
 {
 close(pipe1[0]);
 close(pipe2[1]);
 client(pipe2[0],pipe1[1]);
 while(wait((int *)0)!=childpid)
 close(pipe1[1]);
 close(pipe2[0]);
  exit(1);
  }
  else
  {
  close(pipe1[1]);
  close(pipe2[0]);
  server(pipe1[0],pipe2[1]);
  close(pipe1[0]);
  close(pipe2[1]);
  }
  }
  client(readfd,writefd)
  int readfd,writefd;
  {
  char buff[MAXBUFF];
  int n;
  if(fgets(buff,MAXBUFF,stdin)==NULL)
  printf("client filename read error");
  n=strlen(buff);
  if(buff[n-1]=='n')
  n--;
if(write(writefd,buff,n)!=n)
 printf("client filename error");
 while((n=read(readfd,buff,MAXBUFF))>0)
 if(write(1,buff,n)!=n)
 printf("client data write error");
 if(n>0)
 printf("client: data read errror");
 }
 server(readfd,writefd)
 int readfd,writefd;
 {
 char buff[MAXBUFF];
 int n,fd;
 if((n=read(readfd,buff,MAXBUFF))<0)
 printf("srever filename read error");
 buff[n]='0';
 if((fd=open(buff,0))<0)
 {
 n=strlen(buff);
 if(write(writefd,buff,n)!=n)
 printf("server :error msg");
 }
 else
 {
 while((n=read(fd,buff,MAXBUFF))>0)
 if(write(writefd,buff,n)!=n)
 printf("server data write error");
 if(n>0)
 printf("server read error");
 }
 }


OUTPUT:
vi a.txt
      welcome to NP

    ]$ ./a.out
      a.txt
    welcome to NP
b) FIFO

#include<stdlib.h>
 #include<sys/types.h>
 #include<stdio.h>
 #include<sys/stat.h>
 #include<string.h>
 #include<sys/wait.h>
 #define FIFO1 "tmp/fifo1.c"
 #define FIFO2 "tmp/fifo2.c"
 #define PERM 0666
 main()
 {
 int chpid,rfd,wfd;
 mknod(FIFO1,S_IFIFO|PERM,0);
 mknod(FIFO2,S_IFIFO|PERM,0);
 if(chpid=fork()>0)
 {
 wfd=open(FIFO1,1);
 rfd=open(FIFO2,0);
 client(rfd,wfd);
 while(wait((int *)0)!=chpid)
 close(rfd);
 close(wfd);
 exit(1);
  }
  }




OUTPUT:
 hello
   HELLO :from server
c) Semaphores

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

#define MAX_RETRIES 10

union semun {
   int val;
   struct semid_ds *buf;
   ushort *array;
};

int initsem(key_t key, int nsems)
{
   int i;
   union semun arg;
   struct semid_ds buf;
   struct sembuf sb;
   int semid;

  semid = semget(key, nsems, IPC_CREAT | IPC_EXCL | 0666);

  if (semid >= 0) {
     sb.sem_op = 1; sb.sem_flg = 0;
     arg.val = 1;

     printf("press returnn"); getchar();

     for(sb.sem_num = 0; sb.sem_num < nsems; sb.sem_num++) {

         if (semop(semid, &sb, 1) == -1) {
            int e = errno;
            semctl(semid, 0, IPC_RMID);
            errno = e;
            return -1;
         }
     }

   }
else if (errno == EEXIST)
{
int ready = 0;

       semid = semget(key, nsems, 0);
       if (semid < 0) return semid;
        arg.buf = &buf;
       for(i = 0; i < MAX_RETRIES && !ready; i++)
        {
           semctl(semid, nsems-1, IPC_STAT, arg);
           if (arg.buf->sem_otime != 0)
          {
              ready = 1;
           } else {
              sleep(1);
           }
       }
       if (!ready) {
           errno = ETIME;
           return -1;
       }
    } else {
       return semid;
    }

    return semid;
}

int main(void)
{
   key_t key;
   int semid;
   struct sembuf sb;

    sb.sem_num = 0;
    sb.sem_op = -1;
    sb.sem_flg = SEM_UNDO;

     if ((key = ftok("semdemo.c", 'J')) == -1)
    {
        perror("ftok");
        exit(1);
     }


    if ((semid = initsem(key, 1)) == -1)
    {
       perror("initsem");
       exit(1);
    }
printf("Press return to lock: ");
getchar();
printf("Trying to lock...n");

if (semop(semid, &sb, 1) == -1)
{
   perror("semop");
   exit(1);
}

printf("Locked.n");
printf("Press return to unlock: ");
getchar();

sb.sem_op = 1; /
if (semop(semid, &sb, 1) == -1)
{
    perror("semop");
    exit(1);
  }
 printf("Unlockedn"); return 0;}

 OUTPUT:
d) Message Queues
/*server*/

  #include<sys/types.h>
  #include<sys/ipc.h>
  #include<sys/msg.h>
  #include<stdio.h>
  #include<stdlib.h>
  #include<string.h>
  #define BUFSZ 4096
  struct msg
  { 10 long int type;
  char text[BUFSZ];
 };
 int main()
 {
  struct msg data;
  int msgid;
  char buff[BUFSZ];
  msgid=msgget((key_t)4321,0666|IPC_CREAT);
  while(1)
  { 21 printf("n enter some data:nn");
  fgets(buff,BUFSZ,stdin);
    data.type=1;
   strcpy(data.text,buff);
   msgsnd(msgid,(void *)&data,BUFSZ,0);
   exit(1);
  } 28 }

OUTPUT: enter some data
   hai

/*client*/
 #include<sys/types.h>
 #include<sys/ipc.h>
 #include<sys/msg.h>
 #include<stdio.h>
 #include<stdlib.h>
 #include<string.h>
 #define MSGKEY1 4321L
#define MAX 5700
  typedef struct msgbuf{
 long mtype;
 char mtext[MAX];
 }my_msgbuff;
 main()
{
 my_msgbuff buffer;
 int msgID,myID;
 int temp;
 if((msgID=msgget(MSGKEY1,0666|IPC_CREAT))<0)
 {
perror("error getting msg queue");
 exit(1);
}
 if(msgrcv(msgID,&buffer,sizeof(buffer),0L,0)<0)
 {
 perror("error receiving msg from queue");
 exit(1);
 }
 printf("n msg read from queue:nn");
printf("MESSAGE:%sn",buffer.mtext);
while(msgsnd(msgID,&buffer,sizeof(buffer.mtext),0)>0);
 if(msgctl(msgID,IPC_RMID,0)<0)
{
 perror("error detecting msg queue");
exit(1);
 }
 msgctl(myID,IPC_RMID,0);
 exit(0); }



OUTPUT:
msg read from queue:
    MESSAGE:hai
e) Shared Memory

/*server*/
  #include<sys/types.h>
  #include<sys/ipc.h>
  #include<sys/shm.h>
  #include<stdio.h>
  #include<stdlib.h>
  #define SHMSZ 27
  main()
  {
  char c;
 int shmid;
 key_t key;
 char *shm,*s;
 key=1202;
 if((shmid=shmget(key,SHMSZ,IPC_CREAT|0666))<0)
 {
 perror("shmat");
 exit(1);
 }
 if((shm=shmat(shmid,NULL,0))==(char *)-1)
 {
 perror("shmat");
 exit(1);
 }
 s=shm;
 for(c='a';c<='z';c++)
 *s++=c;
 *s=NULL;
 while(*shm!='*')
 sleep(1);
 exit(0);
 }
/*client*/

 #include<sys/types.h>
#include<sys/ipc.h>
 #include<sys/shm.h>
 #include<stdio.h>
 #include<stdlib.h>
 #define SHMSZ 27
 main()
 {
 int shmid;
 key_t key;
 key=1202;
 char *s,*shm;
 if((shmid=shmget(key,SHMSZ,0666))<0)
 {
 perror("shmget");
 exit(1);
 }
 if((shm=shmat(shmid,NULL,0))==(char *)-1)
  {
    perror("shmat");
    exit(1);
  }
 for(s=shm;*s!=NULL;s++)
 putchar(*s);
 putchar('n');
 *shm='*';
 exit(0);
 }


OUTPUT:
abcdefghijklmnopqrstuvwxyz
Banker’s Algorithm for Deadlock avoidance and Prevention

#include<stdio.h>
#include<conio.h>
int C[4][3],A[4][3],RQ[4][3],V[3],R[3],K[4],sum=0,np,nr;
main()
{
void fun();
int i,j,count=0,pcount=0;
clrscr();
printf("nEnter the total number of resources : ");
scanf("n%d",&nr);
for(i=0;i<nr;i++)
 {
 printf("nEnter the no of resources int R%d : ",i+1);
 scanf("%d",&R[i]);
 }
printf("nEnter the no of processes to be executed : ");
scanf("%d",&np);
printf("nEnter the claim matrix:n");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&C[i][j]);
printf("nEnter the allocation matrix:n");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&A[i][j]);
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
RQ[i][j] = C[i][j] - A[i][j];
fun();
for(i=0;i<np;i++)
{
count=0;
f(K[i] == i+1)
continue;
 for(j=0;j<nr;j++)
 {
 if(V[j] >= RQ[i][j])
 count++;
   }
  if(count == nr)
 {
  K[i] = i+1;
  for(j=0;j<nr;j++)
         C[i][j] = A[i][j] = RQ[i][j] = 0;
        pcount++;
        count = 0;
        i=-1;
        fun();
      }
    }

 if(pcount == np)
  printf("nThere is no chance of deadlock.nIt is a safe state.");
 else
  printf("nThere is a chance of deadlock.nIt isn't a safe state.");
 getch();
 }

 void fun()
 {
 int i1,j1;
 for(i1=0;i1<nr;i1++)
 {
  for(j1=0;j1<np;j1++)
 {
  sum = sum + A[j1][i1];
  }
  V[i1] = R[i1] - sum;
  sum = 0;
  }
  }




OUTPUT
 Enter the total number of resources
 2
 Enter the total number of resources in R1
4
Enter the total number of resources in R2
5
Enter the total number of processes to be executed
4
Enter the claim matrix
2462
Enter the allocation matrix
1011
There is a chance of deadlock
It is not a safe state

More Related Content

What's hot

Programs for Operating System
Programs for Operating SystemPrograms for Operating System
Programs for Operating SystemLPU
 
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)Make Mannan
 
The Ring programming language version 1.7 book - Part 38 of 196
The Ring programming language version 1.7 book - Part 38 of 196The Ring programming language version 1.7 book - Part 38 of 196
The Ring programming language version 1.7 book - Part 38 of 196Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 44 of 212
The Ring programming language version 1.10 book - Part 44 of 212The Ring programming language version 1.10 book - Part 44 of 212
The Ring programming language version 1.10 book - Part 44 of 212Mahmoud Samir Fayed
 
Macroprocessor
MacroprocessorMacroprocessor
Macroprocessorksanthosh
 
C Prog - Strings
C Prog - StringsC Prog - Strings
C Prog - Stringsvinay arora
 
An algorithm for computing resultant polytopes
An algorithm for computing resultant polytopesAn algorithm for computing resultant polytopes
An algorithm for computing resultant polytopesVissarion Fisikopoulos
 
C Prog. - Structures
C Prog. - StructuresC Prog. - Structures
C Prog. - Structuresvinay arora
 
The Ring programming language version 1.4 book - Part 6 of 30
The Ring programming language version 1.4 book - Part 6 of 30The Ring programming language version 1.4 book - Part 6 of 30
The Ring programming language version 1.4 book - Part 6 of 30Mahmoud Samir Fayed
 
Introduction to Polyhedral Compilation
Introduction to Polyhedral CompilationIntroduction to Polyhedral Compilation
Introduction to Polyhedral CompilationAkihiro Hayashi
 
Ştiri de ultima ora si ultimele ştiri Vdtonline.com
Ştiri de ultima ora si ultimele ştiri Vdtonline.comŞtiri de ultima ora si ultimele ştiri Vdtonline.com
Ştiri de ultima ora si ultimele ştiri Vdtonline.comVdtonline.com
 
The Ring programming language version 1.9 book - Part 88 of 210
The Ring programming language version 1.9 book - Part 88 of 210The Ring programming language version 1.9 book - Part 88 of 210
The Ring programming language version 1.9 book - Part 88 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181Mahmoud Samir Fayed
 
RuleML2015: GRAAL - a toolkit for query answering with existential rules
RuleML2015:  GRAAL - a toolkit for query answering with existential rulesRuleML2015:  GRAAL - a toolkit for query answering with existential rules
RuleML2015: GRAAL - a toolkit for query answering with existential rulesRuleML
 

What's hot (19)

Programs for Operating System
Programs for Operating SystemPrograms for Operating System
Programs for Operating System
 
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
 
The Ring programming language version 1.7 book - Part 38 of 196
The Ring programming language version 1.7 book - Part 38 of 196The Ring programming language version 1.7 book - Part 38 of 196
The Ring programming language version 1.7 book - Part 38 of 196
 
Os lab 1st mid
Os lab 1st midOs lab 1st mid
Os lab 1st mid
 
The Ring programming language version 1.10 book - Part 44 of 212
The Ring programming language version 1.10 book - Part 44 of 212The Ring programming language version 1.10 book - Part 44 of 212
The Ring programming language version 1.10 book - Part 44 of 212
 
Computer graphics
Computer graphicsComputer graphics
Computer graphics
 
Macroprocessor
MacroprocessorMacroprocessor
Macroprocessor
 
C Prog - Strings
C Prog - StringsC Prog - Strings
C Prog - Strings
 
An algorithm for computing resultant polytopes
An algorithm for computing resultant polytopesAn algorithm for computing resultant polytopes
An algorithm for computing resultant polytopes
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
C Prog. - Structures
C Prog. - StructuresC Prog. - Structures
C Prog. - Structures
 
The Ring programming language version 1.4 book - Part 6 of 30
The Ring programming language version 1.4 book - Part 6 of 30The Ring programming language version 1.4 book - Part 6 of 30
The Ring programming language version 1.4 book - Part 6 of 30
 
Introduction to Polyhedral Compilation
Introduction to Polyhedral CompilationIntroduction to Polyhedral Compilation
Introduction to Polyhedral Compilation
 
Reactive Collections
Reactive CollectionsReactive Collections
Reactive Collections
 
Ştiri de ultima ora si ultimele ştiri Vdtonline.com
Ştiri de ultima ora si ultimele ştiri Vdtonline.comŞtiri de ultima ora si ultimele ştiri Vdtonline.com
Ştiri de ultima ora si ultimele ştiri Vdtonline.com
 
Ray Tracing with ZIO
Ray Tracing with ZIORay Tracing with ZIO
Ray Tracing with ZIO
 
The Ring programming language version 1.9 book - Part 88 of 210
The Ring programming language version 1.9 book - Part 88 of 210The Ring programming language version 1.9 book - Part 88 of 210
The Ring programming language version 1.9 book - Part 88 of 210
 
The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181
 
RuleML2015: GRAAL - a toolkit for query answering with existential rules
RuleML2015:  GRAAL - a toolkit for query answering with existential rulesRuleML2015:  GRAAL - a toolkit for query answering with existential rules
RuleML2015: GRAAL - a toolkit for query answering with existential rules
 

Viewers also liked

South park middle school
South park middle schoolSouth park middle school
South park middle schoolhvolrie
 
South park middle school
South park middle schoolSouth park middle school
South park middle schoolhvolrie
 
Week 4 - Technology Action Plan
Week 4 - Technology Action PlanWeek 4 - Technology Action Plan
Week 4 - Technology Action Planstevetaylor18
 
Fantastic trip by nasa
Fantastic trip by nasaFantastic trip by nasa
Fantastic trip by nasaChaitanya Kn
 
Neil Armstrong Hall of Engineering
Neil Armstrong Hall of EngineeringNeil Armstrong Hall of Engineering
Neil Armstrong Hall of Engineeringseunghoon91
 
Texas STaR Chart Powerpoint
Texas STaR Chart PowerpointTexas STaR Chart Powerpoint
Texas STaR Chart Powerpointstevetaylor18
 
Jpdcs1 data leakage detection
Jpdcs1 data leakage detectionJpdcs1 data leakage detection
Jpdcs1 data leakage detectionChaitanya Kn
 
Jpdcs1(data lekage detection)
Jpdcs1(data lekage detection)Jpdcs1(data lekage detection)
Jpdcs1(data lekage detection)Chaitanya Kn
 
Black box-software-testing-douglas-hoffman2483
Black box-software-testing-douglas-hoffman2483Black box-software-testing-douglas-hoffman2483
Black box-software-testing-douglas-hoffman2483Chaitanya Kn
 

Viewers also liked (19)

Testing primer
Testing primerTesting primer
Testing primer
 
South park middle school
South park middle schoolSouth park middle school
South park middle school
 
Dbms print
Dbms printDbms print
Dbms print
 
South park middle school
South park middle schoolSouth park middle school
South park middle school
 
Dbms 2
Dbms 2Dbms 2
Dbms 2
 
Presentation1
Presentation1Presentation1
Presentation1
 
Week 4 - Technology Action Plan
Week 4 - Technology Action PlanWeek 4 - Technology Action Plan
Week 4 - Technology Action Plan
 
Ds program-print
Ds program-printDs program-print
Ds program-print
 
Fantastic trip by nasa
Fantastic trip by nasaFantastic trip by nasa
Fantastic trip by nasa
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Stop complaining
Stop complainingStop complaining
Stop complaining
 
Neil Armstrong Hall of Engineering
Neil Armstrong Hall of EngineeringNeil Armstrong Hall of Engineering
Neil Armstrong Hall of Engineering
 
Texas STaR Chart Powerpoint
Texas STaR Chart PowerpointTexas STaR Chart Powerpoint
Texas STaR Chart Powerpoint
 
Jpdcs1 data leakage detection
Jpdcs1 data leakage detectionJpdcs1 data leakage detection
Jpdcs1 data leakage detection
 
Unix lab manual
Unix lab manualUnix lab manual
Unix lab manual
 
Nano tech
Nano techNano tech
Nano tech
 
Jpdcs1(data lekage detection)
Jpdcs1(data lekage detection)Jpdcs1(data lekage detection)
Jpdcs1(data lekage detection)
 
Stm unit1
Stm unit1Stm unit1
Stm unit1
 
Black box-software-testing-douglas-hoffman2483
Black box-software-testing-douglas-hoffman2483Black box-software-testing-douglas-hoffman2483
Black box-software-testing-douglas-hoffman2483
 

Similar to Os 2 cycle

Similar to Os 2 cycle (20)

VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
Coding
CodingCoding
Coding
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligence
 
ADA FILE
ADA FILEADA FILE
ADA FILE
 
C lab manaual
C lab manaualC lab manaual
C lab manaual
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
data structure and algorithm.pdf
data structure and algorithm.pdfdata structure and algorithm.pdf
data structure and algorithm.pdf
 
Lowest common ancestor
Lowest common ancestorLowest common ancestor
Lowest common ancestor
 
Data structure output 1
Data structure output 1Data structure output 1
Data structure output 1
 
Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
 
Sorting programs
Sorting programsSorting programs
Sorting programs
 
week-18x
week-18xweek-18x
week-18x
 
week-17x
week-17xweek-17x
week-17x
 
Ada file
Ada fileAda file
Ada file
 
Datastructures asignment
Datastructures asignmentDatastructures asignment
Datastructures asignment
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
LAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAMLAB PROGRAMS SARASWATHI RAMALINGAM
LAB PROGRAMS SARASWATHI RAMALINGAM
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
Hangman Game Programming in C (coding)
Hangman Game Programming in C (coding)Hangman Game Programming in C (coding)
Hangman Game Programming in C (coding)
 

Recently uploaded

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 

Os 2 cycle

  • 1. Simulate all Page Replacement Algorithms a) FIFO Page Replacement Algorithm #include<stdio.h> #include<conio.h> int str[30],z,count,fs,p[100],pf=0; main() { int i,j,k,temp; printf("n Enter the No.of frames:"); scanf("%d",&fs); printf("n Enter string (-1 to stop):"); i=0; while(1) { scanf("%d",&temp); if(temp==-1) break; str[i++]=temp; } count=i; for(i=0;i<fs;i++) p[i]=-1; printf("nt Pages t Frames"); i=j=0; while(i<count) { if(!check(str[i])) { pf++; p[j]=str[i]; j=(j+1)%fs; } printf("nt <%d> t",str[i]); for(k=0;k<fs;k++) if(p[k]!=-1) printf("%3d",p[k]); i++; } z=pf-fs; printf("nt Page Faults:%d",z); } check(int key) { int i; for(i=0;i<fs;i++) if(key==p[i]) return 1;
  • 2. return 0; } OUTPUT: 1) Enter the No.of frames:3 Enter string (-1 to stop):2 3 2 1 5 2 4 5 3 2 5 2 -1 Pages Frames <2> 2 <3> 2 3 <2> 2 3 <1> 2 3 1 <5> 5 3 1 <2> 5 2 1 <4> 5 2 4 <5> 5 2 4 <3> 3 2 4 <2> 3 2 4 <5> 3 5 4 <2> 3 5 2 Page Faults:6
  • 3. b) LRU Page Replacement Algorithm #include<stdio.h> #include<conio.h> int str[30],count,fs,p[100],pf; main() { int i,j,k,z,temp; printf("n Enter the No.of frames:"); scanf("%d",&fs); printf("n Enter string (-1 to stop):"); i=0; while(1) { scanf("%d",&temp); if(temp==-1) break; str[i++]=temp; } count=i; for(i=0;i<fs;i++) p[i]=-1; printf("n Pages tt Frames"); i=0; while(i<count) { if(!check(str[i])) { pf++; j=lru(i); p[j]=str[i]; } printf("n %3d tt",str[i]); for(k=0;k<fs;k++) if(p[k]!=-1) printf("%3d",p[k]); i++; } z=pf-fs; printf("nn Page Faults:%d",z); } check(int key) { int i; for(i=0;i<fs;i++) if(key==p[i]) return 1; return 0;
  • 4. } lru(int pos) { int i,j=0,r=0; for(i=0;i<fs;i++) { if(p[i]==-1) return i; if(rec(i,pos)>=r) { j=i; r=rec(i,pos); } } return j; } rec(int fn,int pn) { int i,c=0; for(i=pn-1;i>=0;i--) { c++; if(p[fn]==str[i]) return c; } } OUTPUT 1) Enter the No. of frames: 3 Enter string (-1 to stop):2 3 2 1 5 2 4 5 3 2 5 2 -1 Pages Frames 2 2 3 2 3 2 2 3 1 2 3 1 5 2 5 1 2 2 5 1 4 2 5 4 5 2 5 4 3 3 5 4 2 3 5 2 5 3 5 2 2 3 5 2 Page Faults:4
  • 5. c) LFU page replacement Algorithm #include<stdio.h> int i,j=1,s,k,l,re[30],p[10],ch,no,nr,c,a1=0,a,line=6,nk; struct { int st,l,ps,pos; }opr; main() { clrscr(); printf("Enter length of reference string:"); scanf("%d",&nr); printf(" Enter reference string:"); for(i=1;i<=nr;i++) scanf("%d",&re[i]); printf("n Enter number of frames:"); scanf("%d",&no); clrscr(); for(i=1;i<=no;i++) p[i]=-1; opr.st=100; for(i=1;i<=nr;i++) { a1=0; opr.st=100; opr.pos=100; for(c=1;c<=no;c++) if(re[i]==p[c]) a1++; if(a1==0) { if(j<=no) { p[j]=re[i]; j++; } else { for(k=1;k<=no;k++) { a=0; for(ch=i-1;ch>0;ch--) { if(p[k]==re[ch]) { a++; nk=ch; }
  • 6. } if(a>1) { if(opr.st>a) { opr.st=a; opr.ps=k; } else if(opr.st==a) { if(opr.pos>ch) opr.ps=k; } } else if(a==1) { if(opr.pos>nk) { opr.pos=nk; opr.ps=k; opr.st=a; } } } p[(opr.ps)]=re[i]; } } display(no,p,i); } printf("n"); getch(); } display(int no,int p[],int i) { int k; if(i==1) { printf("ttt"); for(k=1;k<=no;k++) printf("_ _"); } printf("n%d",re[i]); gotoxy(25,line++); for(k=1;k<=no;k++) { printf("|"); printf("_"); if(p[k]!=-1)
  • 7. printf("%d",p[k]); else printf(" "); printf("_"); } printf("|"); } OUTPUT: Least frequently used Enter no of frame 3 Enter no of pages 4 Enter page sequence 4 5 8 400F 450F 458F No of page faults 3
  • 8. 3.Simulate all File Allocation Strategies a) Sequential file allocation #include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct { int bno,flag; }block; block b[200]; void main() { int rnum(); int n,p[30],i,j,r,k[20][20],s,s1; printf("n input"); printf("n enter no of files"); scanf("%d",&n); printf("n-------------------------------"); printf("n enter memory requirements"); printf("n------------------------------"); for(i=1;i<=n;i++) { printf("n enter %d file requirements:",i); scanf("%d",&p[i]); } for(i=1;i<=n;i++) { s1=rnum(); j=0; for(s=s1;s<(s1+p[i]);s++) { j=j+1; b[s].bno=s; b[s].flag=1; k[i][j]=s; } } printf("n output"); printf("n ---------------------------------"); printf("n program blocka allocated"); printf("n----------------------------------"); for(i=1;i<=n;i++)
  • 9. { printf("%5dt",i); for(j=1;j<=p[i];j++) printf("%5d",k[i][j]); printf("'n"); } printf("n------------------------------------"); printf("n allocated blocks:"); printf("n-----------------------------------"); for(i=1;i<=200;i++) if(b[i].flag==1) printf("%5dt",b[i].bno); } int rnum() { int i,k=0; for(i=1;i<=200;i++) { k=rand()%200; if(k%2==0) k=k+10; if(b[k].flag!=1) break; return k; } } OUTPUT: Enter the no of input files : 3 Input the requirements: Enter the no of blocks needed in file 1: 2 Enter the no of blocks needed in file2 :4 Enter the no of blocks needed in file3: 3 Allocation Allocate for file1: 8386 Allocate for file2: 77159335 Allocate for file3:924921
  • 10. b) Indexed File allocation #include<stdio.h> #include<conio.h> #include<stdlib.h> struct block { int bno,flag; }; struct block b[100]; int rnum(); void main() { int p[10],r[10][10],ab[10],i,j,n,s; printf("n INPUT"); printf("enter no of files:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("n enter the size of block %d:",i); scanf("%d",&p[i]); } for(i=1;i<=n;i++) { s=rnum(); ab[i]=s; for(j=0;j<p[i];j++) { s=rnum(); r[i][j]=s; } } printf("n output:"); for(i=1;i<=n;i++) { printf("n file %d n block %d contains:",i,ab[i]); for(j=0;j<p[i];j++) { printf("%6d",r[i][j]); } } } int rnum() { int k=0,i; for(i=1;i<=100;i++) {
  • 11. k=rand()%100; if(b[k].flag!=-1) break; } return k; } OUTPUT: Enter the no of files: 3 Enter the memory requirements: Enter the 1 file requirement: 3 Enter the 2 file requirement: 2 Enter the 3 file requirement: 4 Program blocks allocated 1 70 71 72 2 115 116 3 212 213 214 215 Allocated blocks 70 71 72 115 116 212 213 214 215
  • 12. c) Linked File Allocation #include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct { int bno,flag,bn[20]; }block; block b[100],b1; void main() { int rnum(); int p[30],kk[20],i,n,t,s1,s,r,j,c=1; printf("n enter no of i/p files"); scanf("%d",&n); printf("n input the requirements"); for(i=1;i<=n;i++) { printf("n enter the no of blocks needed for file%d",i); scanf("%d",&p[i]); } t=1; for(i=1;i<=n;i++) { for(j=1;j<=p[i];j++) { s=rnum(); b[s].flag=1; b[c].bno=s; r=p[i]-1; kk[i]=s; t=1; c++; } } while(r!=0) { s1=rnum(); b[s].bn[t]=s1; b[s1].flag=1; b[c].bno=s1; r=r-1; t=t+1; c++; } printf("n allocation:n");
  • 13. c=1; for(i=1;i<=n;i++) { printf("n allocated for file%d",i); for(j=1;j<=p[i];j++) { if(j==1) { printf("%3d",b[c].bno); c++; } else { printf("---->%3d",b[c].bno); c++; } } printf("n"); } } int rnum() { int k=0,i; for(i=1;i<=100;i++) { k=rand()%100; if(b[k].flag!=1) break; } return k; } OUTPUT: Enter the no of files 3 Enter the size of block 1 2 3 4 3 2 File 1 Block 83 contains 86 77 15 93 File 2 Block 85 contains 86 92 49 File 3 Block 21 contains 62 27
  • 14. 4. Simulate all File Organization Techniques a) Single level directory #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<graphics.h> void main() { int gd,gm,count,i,j,mid,cir_x; char fname[10][20]; gd=DETECT; clrscr(); initgraph(&gd,&gm,"c:/turboc"); cleardevice(); setbkcolor(GREEN); puts("n Enterno.of files do u have?"); scanf("%d",&count); for(i=0;i<count;i++) { cleardevice(); setbkcolor(GREEN); printf("Enter file %d name ",i+1); scanf("%s",fname[i]); setfillstyle(1,MAGENTA); mid=640/count; cir_x=mid/3; bar3d(270,100,370,150,0,0); settextstyle(2,0,4); settextjustify(1,1); outtextxy(320,125,"Root Directory"); setcolor(BLUE); for(j=0;j<=i;j++,cir_x+=mid) { line(320,150,cir_x,250); fillellipse(cir_x,250,30,30); outtextxy(cir_x,250,fname[i]); } getch(); } }
  • 16. b) Two level Directory //two level directory structure #include<stdio.h> #include<conio.h> #include<graphics.h> #define SX 250 #define SY 200 #define BL 30 #define BW 15 #define SY1 250 int SX1=100; int n,m[10]; char a[10][10]; int cols[]={2,5,1,3,4,6,8,7,9}; typedef struct { char name[10]; struct { char file[10]; }k[10]; }file_info; file_info f[10]; void readfiles() { int i,j; printf("nEnter no. of directories:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter %d directory:",i+1); scanf("%s",&f[i].name); printf("enter no.of files:"); scanf("%d",&m[i]); for(j=0;j<m[i];j++) { printf("enter %d file name:",j+1); scanf("%s",&f[i].k[j].file); } } } void fillspace() { int x1,y1,i,j; outtextxy(70,205,"Directory"); outtextxy(100,255,"Files"); for(i=0;i<n;i++) {
  • 17. setfillstyle(1,cols[i]); x1=SX+(i%10)*50; y1=SY+(i/10)*40; bar(x1,y1,x1+BL+20,y1+BW); outtextxy(x1+BL/4,y1+BW/4,f[i].name); line(x1+BL/2,y1+BW,SX1+50,SY1); SX1=SX1+50; for(j=0;j<m[i];j++) { setfillstyle(1,cols[i]); x1=SX1+(j%10)*40; y1=SY1+(j/10)*40; bar(x1,y1,x1+BL+10,y1+BW); outtextxy(x1+BL/4,y1+BW/4,f[i].k[j].file); line(x1+BL/2,y1+BW,x1+BL/2,y1+50); circle(x1+BL/2,y1+60,7); } SX1=SX1+100; } } void main() { int gm,gd=DETECT; initgraph(&gd,&gm,"c:tcbgi"); readfiles(); cleardevice(); getch(); fillspace(); getch(); closegraph(); }
  • 18. 5.Interprocess Communication a) Pipes #include<stdio.h> #include<string.h> #include<stdlib.h> #include<error.h> #define MAXBUFF 1024 main() { int childpid,pipe1[2],pipe2[2]; if(pipe(pipe1)<0||pipe(pipe2)<0) printf("error"); if((childpid=fork())<0) { printf("error"); } else if(childpid>0) { close(pipe1[0]); close(pipe2[1]); client(pipe2[0],pipe1[1]); while(wait((int *)0)!=childpid) close(pipe1[1]); close(pipe2[0]); exit(1); } else { close(pipe1[1]); close(pipe2[0]); server(pipe1[0],pipe2[1]); close(pipe1[0]); close(pipe2[1]); } } client(readfd,writefd) int readfd,writefd; { char buff[MAXBUFF]; int n; if(fgets(buff,MAXBUFF,stdin)==NULL) printf("client filename read error"); n=strlen(buff); if(buff[n-1]=='n') n--;
  • 19. if(write(writefd,buff,n)!=n) printf("client filename error"); while((n=read(readfd,buff,MAXBUFF))>0) if(write(1,buff,n)!=n) printf("client data write error"); if(n>0) printf("client: data read errror"); } server(readfd,writefd) int readfd,writefd; { char buff[MAXBUFF]; int n,fd; if((n=read(readfd,buff,MAXBUFF))<0) printf("srever filename read error"); buff[n]='0'; if((fd=open(buff,0))<0) { n=strlen(buff); if(write(writefd,buff,n)!=n) printf("server :error msg"); } else { while((n=read(fd,buff,MAXBUFF))>0) if(write(writefd,buff,n)!=n) printf("server data write error"); if(n>0) printf("server read error"); } } OUTPUT: vi a.txt welcome to NP ]$ ./a.out a.txt welcome to NP
  • 20. b) FIFO #include<stdlib.h> #include<sys/types.h> #include<stdio.h> #include<sys/stat.h> #include<string.h> #include<sys/wait.h> #define FIFO1 "tmp/fifo1.c" #define FIFO2 "tmp/fifo2.c" #define PERM 0666 main() { int chpid,rfd,wfd; mknod(FIFO1,S_IFIFO|PERM,0); mknod(FIFO2,S_IFIFO|PERM,0); if(chpid=fork()>0) { wfd=open(FIFO1,1); rfd=open(FIFO2,0); client(rfd,wfd); while(wait((int *)0)!=chpid) close(rfd); close(wfd); exit(1); } } OUTPUT: hello HELLO :from server
  • 21. c) Semaphores #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #define MAX_RETRIES 10 union semun { int val; struct semid_ds *buf; ushort *array; }; int initsem(key_t key, int nsems) { int i; union semun arg; struct semid_ds buf; struct sembuf sb; int semid; semid = semget(key, nsems, IPC_CREAT | IPC_EXCL | 0666); if (semid >= 0) { sb.sem_op = 1; sb.sem_flg = 0; arg.val = 1; printf("press returnn"); getchar(); for(sb.sem_num = 0; sb.sem_num < nsems; sb.sem_num++) { if (semop(semid, &sb, 1) == -1) { int e = errno; semctl(semid, 0, IPC_RMID); errno = e; return -1; } } } else if (errno == EEXIST) {
  • 22. int ready = 0; semid = semget(key, nsems, 0); if (semid < 0) return semid; arg.buf = &buf; for(i = 0; i < MAX_RETRIES && !ready; i++) { semctl(semid, nsems-1, IPC_STAT, arg); if (arg.buf->sem_otime != 0) { ready = 1; } else { sleep(1); } } if (!ready) { errno = ETIME; return -1; } } else { return semid; } return semid; } int main(void) { key_t key; int semid; struct sembuf sb; sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = SEM_UNDO; if ((key = ftok("semdemo.c", 'J')) == -1) { perror("ftok"); exit(1); } if ((semid = initsem(key, 1)) == -1) { perror("initsem"); exit(1); }
  • 23. printf("Press return to lock: "); getchar(); printf("Trying to lock...n"); if (semop(semid, &sb, 1) == -1) { perror("semop"); exit(1); } printf("Locked.n"); printf("Press return to unlock: "); getchar(); sb.sem_op = 1; / if (semop(semid, &sb, 1) == -1) { perror("semop"); exit(1); } printf("Unlockedn"); return 0;} OUTPUT:
  • 24. d) Message Queues /*server*/ #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #define BUFSZ 4096 struct msg { 10 long int type; char text[BUFSZ]; }; int main() { struct msg data; int msgid; char buff[BUFSZ]; msgid=msgget((key_t)4321,0666|IPC_CREAT); while(1) { 21 printf("n enter some data:nn"); fgets(buff,BUFSZ,stdin); data.type=1; strcpy(data.text,buff); msgsnd(msgid,(void *)&data,BUFSZ,0); exit(1); } 28 } OUTPUT: enter some data hai /*client*/ #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #define MSGKEY1 4321L
  • 25. #define MAX 5700 typedef struct msgbuf{ long mtype; char mtext[MAX]; }my_msgbuff; main() { my_msgbuff buffer; int msgID,myID; int temp; if((msgID=msgget(MSGKEY1,0666|IPC_CREAT))<0) { perror("error getting msg queue"); exit(1); } if(msgrcv(msgID,&buffer,sizeof(buffer),0L,0)<0) { perror("error receiving msg from queue"); exit(1); } printf("n msg read from queue:nn"); printf("MESSAGE:%sn",buffer.mtext); while(msgsnd(msgID,&buffer,sizeof(buffer.mtext),0)>0); if(msgctl(msgID,IPC_RMID,0)<0) { perror("error detecting msg queue"); exit(1); } msgctl(myID,IPC_RMID,0); exit(0); } OUTPUT: msg read from queue: MESSAGE:hai
  • 26. e) Shared Memory /*server*/ #include<sys/types.h> #include<sys/ipc.h> #include<sys/shm.h> #include<stdio.h> #include<stdlib.h> #define SHMSZ 27 main() { char c; int shmid; key_t key; char *shm,*s; key=1202; if((shmid=shmget(key,SHMSZ,IPC_CREAT|0666))<0) { perror("shmat"); exit(1); } if((shm=shmat(shmid,NULL,0))==(char *)-1) { perror("shmat"); exit(1); } s=shm; for(c='a';c<='z';c++) *s++=c; *s=NULL; while(*shm!='*') sleep(1); exit(0); } /*client*/ #include<sys/types.h>
  • 27. #include<sys/ipc.h> #include<sys/shm.h> #include<stdio.h> #include<stdlib.h> #define SHMSZ 27 main() { int shmid; key_t key; key=1202; char *s,*shm; if((shmid=shmget(key,SHMSZ,0666))<0) { perror("shmget"); exit(1); } if((shm=shmat(shmid,NULL,0))==(char *)-1) { perror("shmat"); exit(1); } for(s=shm;*s!=NULL;s++) putchar(*s); putchar('n'); *shm='*'; exit(0); } OUTPUT: abcdefghijklmnopqrstuvwxyz
  • 28. Banker’s Algorithm for Deadlock avoidance and Prevention #include<stdio.h> #include<conio.h> int C[4][3],A[4][3],RQ[4][3],V[3],R[3],K[4],sum=0,np,nr; main() { void fun(); int i,j,count=0,pcount=0; clrscr(); printf("nEnter the total number of resources : "); scanf("n%d",&nr); for(i=0;i<nr;i++) { printf("nEnter the no of resources int R%d : ",i+1); scanf("%d",&R[i]); } printf("nEnter the no of processes to be executed : "); scanf("%d",&np); printf("nEnter the claim matrix:n"); for(i=0;i<np;i++) for(j=0;j<nr;j++) scanf("%d",&C[i][j]); printf("nEnter the allocation matrix:n"); for(i=0;i<np;i++) for(j=0;j<nr;j++) scanf("%d",&A[i][j]); for(i=0;i<np;i++) for(j=0;j<nr;j++) RQ[i][j] = C[i][j] - A[i][j]; fun(); for(i=0;i<np;i++) { count=0; f(K[i] == i+1)
  • 29. continue; for(j=0;j<nr;j++) { if(V[j] >= RQ[i][j]) count++; } if(count == nr) { K[i] = i+1; for(j=0;j<nr;j++) C[i][j] = A[i][j] = RQ[i][j] = 0; pcount++; count = 0; i=-1; fun(); } } if(pcount == np) printf("nThere is no chance of deadlock.nIt is a safe state."); else printf("nThere is a chance of deadlock.nIt isn't a safe state."); getch(); } void fun() { int i1,j1; for(i1=0;i1<nr;i1++) { for(j1=0;j1<np;j1++) { sum = sum + A[j1][i1]; } V[i1] = R[i1] - sum; sum = 0; } } OUTPUT Enter the total number of resources 2 Enter the total number of resources in R1
  • 30. 4 Enter the total number of resources in R2 5 Enter the total number of processes to be executed 4 Enter the claim matrix 2462 Enter the allocation matrix 1011 There is a chance of deadlock It is not a safe state