Tuesday, June 24, 2014

SIMULATE THE FOLLOWING FILE ORGANIZATION TECHNIQUES : A. SINGLE LEVEL DIRECTORY B) TWO LEVEL


SIMULATE THE FOLLOWING FILE ORGANIZATION TECHNIQUES :
A. SINGLE LEVEL DIRECTORY
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm,count,i,j,mid,cir_x;
char fname[10][20];
clrscr();
initgraph(&gd,&gm,"c:/tc/bgi");
cleardevice();
setbkcolor(GREEN);
printf("enter number of files");
scanf("&d",&count);
if(i<count)
// for(i=0;i<count;i++)
{
cleardevice();
setbkcolor(GREEN);
printf("enter %d file 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);
i++;
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:-
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"null",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\tc\bgi");
display(root);
getch();
closegraph();
}
create(node **root,int lev ,char *dname,int lx,int rx,int x)
{
int i, gap;
if(*root==NULL)
{
(*root)=(node*)malloc(sizeof(node));
printf("enter the name of ir file name %s",dname);
fflush(stdin);
gets((*root)->name);
if(lev==0 || lev==1)
(*root)-> ftype=1;
else
(*root)->ftype=2;
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx ;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
if(lev==0 || lev==1)
{
if((*root)->level==0)
printf("how many users");
else
printf(" how many files");
printf("(for %s):",(*root)->name);
scanf("%d",&(*root)->nc);
}
else
(*root)->nc=0;
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)->name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20, root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}

}
output:-

SIMULATE BANKERS ALGORITHM FOR DEAD LOCK DETECTION


SIMULATE BANKERS ALGORITHM FOR DEAD LOCK DETECTION:-
#include<stdio.h>
#include<conio.h>
int max[10][10],alloc[10][10],need[10][10],avail[10],i,j,p,r,finish[10]={0},flag=0;
main( )
{
clrscr( );
printf("\n\nSIMULATION OF DEADLOCK PREVENTION");
printf("Enter no. of processes, resources");
scanf("%d%d",&p,&r);
printf("Enter allocation matrix");
for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&alloc[i][j]);
printf("enter max matrix");
for(i=0;i<p;i++) /*reading the maximum matrix and availale matrix*/
for(j=0;j<r;j++)
scanf("%d",&max[i][j]);
printf("enter available matrix");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
for(i=0;i<p;i++)
for(j=0;j<r;j++)
need[i][j]=max[i][j]-alloc[i][j];
fun(); /*calling function*/
if(flag==0)
{
if(finish[i]!=1)
{
printf("\n\n Failing :Mutual exclusion");
for(j=0;j<r;j++)
{ /*checking for mutual exclusion*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}
fun();
printf("\n By allocating required resources to process %d dead lock is prevented ",i);
printf("\n\n lack of preemption");
for(j=0;j<r;j++)
{
if(avail[j]<need[i][j])
avail[j]=need[i][j];
alloc[i][j]=0;
}
fun( );
printf("\n\n daed lock is prevented by allocating needed resources");
printf(" \n \n failing:Hold and Wait condition ");
for(j=0;j<r;j++)
{ /*checking hold and wait condition*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}
fun();
printf("\n AVOIDING ANY ONE OF THE CONDITION, U CAN PREVENT DEADLOCK");
}
}
getch( );
}
fun( )
{
while(1)
{
for(flag=0,i=0;i<p;i++)
{
if(finish[i]==0)
{
for(j=0;j<r;j++)
{
if(need[i][j]<=avail[j])
continue;
else
break;
}
if(j==r)
{
for(j=0;j<r;j++)
avail[j]+=alloc[i][j];
flag=1;
finish[i]=1;
}
}
}
if(flag==0)
break;
}
}
output:-

SIMULATE BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE


SIMULATE BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE:
#include<stdio.h>
#include<conio.h>
main()
{
int a[10][10],c[10][10],r[10],av[10],ca[10][10],i,j,k,n,m,temp=0,tem,ch;
clrscr();
printf("enter no processes");
scanf("%d",&m);
printf("enter no of resources");
scanf("%d",&n);
printf("\nenter claim\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&c[i][j]);
printf("\nenter alocation matrix\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nenter resourse vector\n");
for(i=0;i<n;i++)
scanf("%d",&r[i]);
k=0;
do
{
printf("claim\tallocation\tca\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%3d",c[i][j]);printf("\t");
for(j=0;j<n;j++)
printf("%3d",a[i][j]);printf("\t\t");
for(j=0;j<n;j++)
{
ca[i][j]=c[i][j]-a[i][j];
printf("%3d",ca[i][j]);
}
printf("\n");
}
temp=0;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
temp=temp+a[j][i];
av[i]=r[i]-temp;temp=0;
}
printf("\nresource vector: ");
for(i=0;i<n;i++)
printf("%3d",r[i]);
printf("\navailable vector: ");
for(i=0;i<n;i++)
printf("%3d",av[i]);
if(k==0)
printf("\n****initial state****\n");
else
printf("\n***p%d runs to completion*****\n",tem+1);
if(k<n)
{
temp=0;
for(i=0;i<m;i++)
{
lab:for(j=0;j<n;j++)
{
if(ca[i][j]==0)
temp++;
}
if(temp==n)
{
i++; temp=0;goto lab;
}
else
{
for(j=0;j<n;j++)
{
if(ca[i][j]<=av[j])
tem=i;
else
{
if(i>m)
{
printf("\nunshafe state");goto end;
}
else
{i++;goto lab;}
}
}
}
for(j=0;j<n;j++)
{
a[tem][j]=0;c[tem][j]=0;ca[tem][j]=0;
}
break;
}
}
else
{
printf("\nprocesses are completed");
goto end;
}
k++;
printf("continue press ZERO");
scanf("%d",&ch);
}while(ch==0);
end: getch();

}
OUTPUT:-

Friday, June 20, 2014

CPU SCHEDULING ALGORITHMS:


Simulate the following CPU scheduling algorithms :
a) Round Robin    b) SJF    c) FCFS     d) Priority
-------------------------------------------------------------------------------------------------------------------------
A) ROUND ROBIN:
#include<stdio.h>
#include<conio.h>
struct process
{
int at,ts,st,ft,wait,ts2,ta;
float nta;
}p[20];
main()
{
int i,j,slice,n;
float tamean=0,ntamean=0;
clrscr();
printf("Enter Number of Processes :: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Arrival Time for Process-%c : ",65+i);
scanf("%d",&p[i].at);
printf("\nEnter Service Time for process-%c : ",65+i);
scanf("%d",&p[i].ts);
}
printf("\nEnter Time Slice: ");
scanf("%d",&slice);
for(i=0;i<n+1;i++)
{
if(i==0)
p[i].ts2=n*slice;
else
p[i].ts2=p[i-1].ts2+(p[i-1].ts-slice);
if(i<n)
p[i].st=i*slice;
if(i>=1)
p[i-1].ft=p[i].ts2;
}
for(i=0;i<n;i++)
p[i].wait=(i*slice-p[i].at)+(p[i].ts2-(i+1)*slice);
for(i=0;i<n;i++)
{
p[i].ta=p[i].ft-p[i].at;
p[i].nta=(float)p[i].ta/p[i].ts;
tamean=tamean+p[i].ta;
ntamean=ntamean+p[i].nta;
}
tamean=(float)tamean/n;
ntamean=(float)ntamean/n;
printf("\n Process AT ST StT FT WT TA NTA\n");
for(i=0;i<n;i++)
{
printf("Process-%c%9d%9d%12d%12d%10d%6d%10.4f",65+i,p[i].at,p[i].ts,p[i].st,p[i].ft,p[i].wait,p[i].ta,p[i].nta);
printf("\n");
}
printf("\nturn around mean is : %f",tamean);
printf("\nnorm.turn around mean is : %f",ntamean);
getch();
}
OUTPUT:-
Image
---------------------------------------------------------------------------------------------------------------------------------------------------
b) SJF:-
#include<stdio.h>
#include<conio.h>
main()
{
int sbt[10],swt[10],st[10],stt[10],sft[10];
int n,i,j,wt,tt,temp;
float avgwt,avgtt;
wt=0;tt=0;temp=0;st[1]=0;
clrscr();
printf("enter no.of jobs");
scanf("%d",&n);
printf("enter the burst times of jobs");
for(i=1;i<=n;i++)
scanf("%d",&sbt[i]);
for(i=1;i<=(n-1);i++)
for(j=i+1;j<=n;j++)
if((sbt[i]>sbt[j])&&(sbt[i]!=sbt[j]))
{
temp=sbt[i];
sbt[i]=sbt[j];
sbt[j]=temp;
}
for(i=1;i<=n;i++)
{ st[i+1]=st[i]+sbt[i];
sft[i]=st[i]+sbt[i];
if(i==1)
swt[i]=0;
else
swt[i]=swt[i-1]+sbt[i-1];
stt[i]=swt[i]+sbt[i];
wt=wt+swt[i];
tt=tt+stt[i];
} avgwt=((float)wt/(float)n);
avgtt=((float)tt/(float)n);
printf("\nJOB sert st wt ft turt");
for(i=1;i<=n;i++)
printf("\nJ%d\t%d\t%d\t %d\t%d\t%d\n",i,sbt[i],st[i],sft[i],swt[i],stt[i]);
printf("\navg waiting time=%0.2f,turnover total time=%0.2f",avgwt,avgtt);
getch();
}
output:-
Image
------------------------------------------------------------------------------------------------------------------------------------------------------
c) FCFS:-
#include<stdio.h>
#include<conio.h>
struct process
{
int at,ts,st,ft,ta;
float nta;
};
main()
{
struct process p[20];
int n,i,j;
float tamean=0,ntamean=0;
clrscr();
printf("\nEnter Number of Processes:: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Arrival Time for Process-%c :: ",65+i);
scanf("%d",&p[i].at);
printf("\nEnter Service Time for Process-%c :: ",65+i);
scanf("%d",&p[i].ts);
}
for(i=0;i<n;i++)
{
if(i==0)
p[i].st=p[i].at;
else
{
p[i].st=0;
for(j=0;j<i;j++)
p[i].st=p[i].st+p[j].ts;
}
p[i].ft=p[i].ts+p[i].st;
p[i].ta=p[i].ft-p[i].at;
p[i].nta=(float)p[i].ta/p[i].ts;
tamean=tamean+p[i].ta;
ntamean=ntamean+p[i].nta;
}
tamean=(float)(tamean/n);
ntamean=(float)(ntamean/n);
printf("\nProcess AT ST StT FT TA NTA");
for(i=0;i<n;i++)
printf("\n%3c%12d%10d%10d%10d%10d%15f",65+i,p[i].at,p[i].ts, p[i].st,p[i].ft,p[i].ta,p[i].nta);
printf("\n\n Mean of Turn-around time : %f",tamean);
printf("\n\n Mean of Normalized turn-around time : %f",ntamean);
getch();
}
output:-
Image
-----------------------------------------------------------------------------------------------------------------------------------------------
d) Priority:-
#include<stdio.h>
#include<conio.h>
struct process
{
int ts,pri,wait,ft;
}p[20];
main()
{
int n,pri1[20],i,j,temp,ft1[25];
clrscr();
printf("\n Enter Number of Processes:: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Service Time for Process-%c : ",65+i);
scanf("%d",&p[i].ts);
printf("\nEnter Priority for Process-%c : ",65+i);
scanf("%d",&p[i].pri);
}
for(i=0;i<n;i++)
pri1[i]=p[i].pri;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(pri1[i]>pri1[j])
{
temp=pri1[i];
pri1[i]=pri1[j];
pri1[j]=temp;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(pri1[i]==p[j].pri)
{
if(i==0)
{
p[j].wait=0;
p[j].ft=p[j].ts;
ft1[i]=p[j].ft;
}
else
{
p[j].ft=ft1[i-1]+p[j].ts;
p[j].wait=ft1[i-1];
ft1[i]=p[j].ft;
}
}
}
}
printf("\nProcess ST PRI FT WT ");
for(i=0;i<n;i++)
{
printf("\nprocess-%c%10d%13d%14d%15d",65+i,p[i].ts,p[i].pri,p[i].ft,p[i].wait);
}
getch();
}
output:-
Image
----------------------------------------------------------------------------------------------------------------------------------------

SIMULATE MVT AND MFT


Simulation of Multiprogramming with Variable and Fixed number of Tasks:-
MVT:-
#include<stdio.h>
#include<conio.h>
main()
{
static int jobs[20][20],flag[10];
int ch;
static int i,k,nj,nb,tms;
clrscr();
printf("Enter time"); /* reading time */
scanf("%d",&tms);
printf("Enter no. of jobs"); /* reading no of jobs */
scanf("%d",&nj);
printf("Enter job information 1.jobid 2.jobsize");
for(i=0;i<nj;i++)
scanf("%d%d",&jobs[i][0],&jobs[i][1]);
for(i=0;i<nj;i++)
{
if(tms>=jobs[i][1])
{
tms=tms-jobs[i][1];
nb=nb+1;
flag[i]=1;
}
}
printf("Total memory space available which is not allocated is:%d\n",tms);
printf("Jobs which are not allocated:");
for(i=0;i<nj;i++)
if(flag[i]==0)
printf("%d\t%d\n",jobs[i][0],jobs[i][1]);
if(nb!=nj)
{
while(1)
{
printf("enter jobid to deallocate:");
scanf("%d",&k);
for(i=0;i<nj;i++)
{
if(jobs[i][0]==k)
{
if(flag[i]==1)
{
tms=tms+jobs[i][1];
flag[i]=2;
printf("Deallocated job %d\t%d\n", jobs[i][0],jobs[i][1]);
}
}
}
for(i=0;i<nj;i++)
{
if (tms>=jobs[i][1])
{
if(flag[i] == 0)
{
tms=tms-jobs[i][1];
flag[i]=1;
}
}
}
printf("Remaining memory is: %d",tms);
printf("Jobs which are not allocated are:");
for( i=0;i<nj;i++) /* dellocating mamory*/
if(flag[i] ==0)
printf("%d\t%d\n", jobs[i][0],jobs[i][1]);
printf("Do you want to deallocate 1.Yes 2.No");
scanf("%d",&ch);
if(ch ==2)
break;
}
}
printf("Allocated jobs are:");
for(i=0;i<nj;i++)
if(flag[i]==1)
printf("%d\t%d\n",jobs[i][0],jobs[i][1]);
getch();
}
output:-
Image
_________________________________________________________________________________________
MFT:-
#include<stdio.h>
#include<conio.h>
void main()
{
int tms,element,nb,i,j,t,index,frag,ch,count=0;
static int jobs[20][20],sz[20][20],nj,s;
clrscr();
printf("enter total memory space"); /* reading memory */
scanf("%d",&tms); /* reading choices */
printf("enter choice\n1.equal partition 2.unequal partition\n");
scanf("%d",&ch);
if(ch==1)
{
printf("enter size of each block");
scanf("%d",&s);
nb=tms/s;
for(i=0;i<nb;i++)
scanf("%d",&sz[i][0]);
}
else
{
printf("enter no. of blocks");
scanf("%d",&nb);
printf("enter size of %d blocks");
for(i=0;i<nb;i++)
scanf("%d",sz[i][0]);
}
printf("enter no. of jobs"); /* reading no of jobs */
scanf("%d",&nj);
printf("enter job information 1.jobid 2.job size\n");
for(i=0;i<nj;i++)
scanf("%d%d",&jobs[i][0],&jobs[i][1]);
frag=0;
for(j=0;j<nj;j++)
{
if(sz[j][0]>=element && sz[i][0]<=t)
{
if(sz[j][1]!=1)
{
t=sz[j][0];
index=j;
}
}
}
if(sz[index][1]!=1)
{
sz[index][1]=1;
jobs[i][2]=2;
frag=frag+(t-element);
count++;
}
printf("total internal fragmentation : %d", frag);
printf("no. of free blocks: %d" , nb-count);
printf("the jobs which are not allocated");
if(count==nj)
printf(" 0");
for(i=0;i<nj;i++)
{
if(jobs[i][2]!=2)
printf("jobid ------%d\tjob size-----%d\n",jobs[i][0],jobs[i][1]);
}
getch();
}
output:-
Image

____________________________________________________________________________________________

SIMULATE PAGE REPLACEMENT ALGORITHMS


Simulate the following Page Replacement algorithms :
a) FIFO b) LRU c) LFU
Page Replacement algorithm-FIFO:-
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{ char prs[40],fp[10],ps;
int fs,i,j,k=0,flg1,flg2,x=5,y,pfc=0;
clrscr();
printf("\n enter page reference string:");
gets(prs);
printf("\n enter the frame size:");
scanf("%d",&fs);
for(i=0;i<fs;i++)
fp[i]='x';
clrscr();
printf("\n page replacement technique :: FIFO algorithm:");
printf("\n .............................................");
printf("\n F-Page Fault \t H- Page Hit \n");
for(i=0;i<strlen(prs);i++,x+=2)
{
flg1=0;
ps='F';
for(j=0;j<fs;j++)
if(fp[j]==prs[i]){
ps='H';
flg1=1;
break;
}
if(flg1==0)
{
flg2=0;
for(j=0;j<fs;j++)
if(fp[j]=='x')
{
fp[j]=prs[i];
pfc++;
flg2=1;
break;
}
if(flg2==0)
{
pfc++;
fp[k]=prs[i];
k++;
if(k==fs)
k=0; } }
y=5;
gotoxy(x,y);
printf("%c",prs[i]);
y++;
gotoxy(x,y);
printf("--");
y++;
for(j=0;j<fs;y++,j++)
{
gotoxy(x,y);
printf("%c",fp[j]);
}
y++;
gotoxy(x,y);
printf("--");
y++;
gotoxy(x,y);
printf("%c",ps);
}
printf("\n \n\n\n\n Total page Faults=%d",pfc);
getch();
}
output:-
Image
___________________________________________________________________________________________
Page Replacement algorithm-LRU:-
#include<dos.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{ char prs[40],fp[10],ps;
int fs,i,j,k,flg1,flg2,x=5,y,pfc=0,ru[10],min;
clrscr();
printf("enter the page reference string:");
gets(prs);
printf("enter the frame size:");
scanf("%d",&fs);
for(i=0;i<fs;i++)
{
fp[i]='x';
ru[i]=0;
}
clrscr();
printf("PAGE REPLACEMENT TECHNIQUE::LRU algorithm\n");
printf("-----------------------------------\n");
printf("F-Page fault\tH-Page Hit\n");
for(i=0;i<strlen(prs);i++,x+=2)
{
flg1=0;
ps='F';
for(j=0;j<fs;j++)
{
if(fp[j]==prs[i])
{
ps='H';
ru[j]=i;
flg1=1;
break;
} }
if(flg1==0)
{
pfc++;
flg2=0;
for(j=0;j<fs;j++)
{
if(fp[j]=='X')
{
fp[j]=prs[i];
ru[j]=i;
flg2=1;
break;
} }
if(flg2==0)
{
min=0;
for(j=1;j<fs;j++)
{
if(ru[min]>ru[j])
min=j;
}
fp[min]=prs[i];
ru[min]=i;
} }
y=5;
gotoxy(x,y);
printf("%c",prs[i]);
y++;
gotoxy(x,y);
printf("- -");
y++;
for(j=0;j<fs;y++,j++)
{
gotoxy(x,y);
printf("%c",fp[j]);
}
y++;
gotoxy(x,y);
printf("--");
y++;
gotoxy(x,y);
printf("%c",ps);
}
printf("\n\n\n\n\n\n total page faults=%d",pfc);
getch();
}
output:-
Image
___________________________________________________________________________________________
Page Replacement algorithm-LFU:-
#include<dos.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{ char prs[40],fp[10],ps;
int fs,i,j,k,flg1,flg2,x=5,y,pfc=0,ru[10],min;
clrscr();
printf("\n ENTER THE PAGE REFERENCE STRING:");
gets(prs);
printf("\n enter the frame size:");
scanf("%d",&fs);
for(i=0;i<fs;i++)
{
fp[i]='X';
ru[i]=0;
} clrscr();
printf("\n PAGE REPLACEMENT TECHNIQUE ::LFU ALGORITHM \n");
printf("\n .......................................... \n");
printf("F-Page Fault \t H-Page Hit\n");
for(i=0;i<strlen(prs);i++,x+=5)
{
flg1=0;
ps='F';
for(j=0;j<fs;j++)
{
if(fp[j]==prs[i])
{
ps='H';
(ru[j])++;
flg1=1;
break;
}}
if(flg1==0)
{
pfc++;
flg2=0;
for(j=0;j<fs;j++)
{
if(fp[j]=='X')
{
fp[j]=prs[i];
ru[j]=1;
flg2=1;
break;
}}
if(flg2==0)
{
min=0;
for(j=1;j<fs;j++)
{
if(ru[min]>=ru[j])
{
if(ru[min]>ru[j])
min=j;
else
{
for(k=0;k<i;k++)
{
if(prs[k]==fp[min])
break;
if(prs[k]==fp[j])
{
min=j;
break;
}}}}}
fp[min]=prs[i];
ru[min]=1;
}}
y=5;
gotoxy(x,y);
printf("%c",prs[i]);
y++;
gotoxy(x,y);
printf("-----");
y++;
for(j=0;j<fs;y++,j++)
{
gotoxy(x,y);
printf("%c(%d)",fp[j],ru[j]);
}
y++;
gotoxy(x,y);
printf("-----");
y++;
gotoxy(x,y);
printf("%c",ps);
}
printf("\n\n\n\n\n TOTAL PAGE FAULTS =%d",pfc);
getch();
}
output:-
Image
___________________________________________________________________________________________

SIMULATE PAGING TECHNIQUE OF MEMORY MANAGEMENT


Simulation of Paging technique of Memory Management:-
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int size,m,n,pgno,pagetable[3]={5,6,7},i,j,frameno;
double m1;
int ra=0,ofs;
clrscr();
printf("Enter process size (in KB of max 12KB):");/*reading memeory size*/
scanf("%d",&size);
m1=size/4;
n=ceil(m1);
printf("Total No. of pages: %d",n);
printf("\nEnter relative address (in hexadecimal notation eg.0XRA) \n");
//printf("The length of relative Address is : 16 bits \n\n The size of offset is :12 bits\n");
scanf("%d",&ra);
pgno=ra/1000; /*calculating physical address*/
ofs=ra%1000;
printf("page no=%d\n",pgno);
printf("page table");
for(i=0;i<n;i++)
printf("\n %d [%d]",i,pagetable[i]);
frameno=pagetable[pgno];
printf("\n Equivalent physical address : %d%d",frameno,ofs);
getch();
}
output:-
Image

Wednesday, June 18, 2014

C PROGRAM THAT ILLUSTRATES THE FOLLOWING: a. Creating a message queue. b. Writing to a message queue. c. Reading from a message queue.



C PROGRAM THAT ILLUSTRATES THE FOLLOWING:
   a. Creating a message queue.
   b. Writing to a message queue.
   c. Reading from a message queue.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include <fcntl.h>
 #define MAX 255
        struct mesg
        {
              long type;
              char mtext[MAX];
        }*mesg;
        char buff[MAX];
 main()
 {
        int mid,fd,n,count=0;
        if((mid=msgget(1006,IPC_CREAT | 0666))<0)
        {
                printf("\n Can’t create Message Q");
                exit(1);
        }
        printf("\n Queue id:%d", mid);
        mesg=(struct mesg *)malloc(sizeof(struct mesg));
        mesg->type=6;
        fd=open("fact",O_RDONLY);
        while(read(fd,buff,25)>0)
        {
                strcpy(mesg->mtext,buff);
                if(msgsnd(mid,mesg,strlen(mesg->mtext),0)== -1)
                     printf("\n Message Write Error");
        }
       if((mid=msgget(1006,0))<0)
        {
                printf("\n Can’t create Message Q");
                exit(1);
        }
        while((n=msgrcv(mid,&mesg,MAX,6,IPC_NOWAIT))>0)
                write(1,mesg->mtext,n);
                count++;
        if((n==-1)&(count==0))
                printf("\n No Message Queue on Queue:%d",mid);
 }
 

Monday, June 16, 2014

INTER-PROCESS COMMUNICATION USING SHARED MEMORY SYSTEM CALL


C program that illustrates inter process communication using shared memory system calls:-
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#define SEGSIZE 100
int main(int argc, char *argv[ ])
{
int shmid,cntr;
key_t key;
char *segptr;
char buff[]="poooda......";
key=ftok(".",'s');
if((shmid=shmget(key, SEGSIZE, IPC_CREAT | IPC_EXCL | 0666))== -1)
{
if((shmid=shmget(key,SEGSIZE,0))==-1)
{
perror("shmget");
exit(1);
}
}
else
{
printf("Creating a new shared memory seg \n");
printf("SHMID:%d",shmid);
}
system("ipcs –m");
if((segptr=(char*)shmat(shmid,0,0))==(char*)-1)
{
perror("shmat");
exit(1);
}
printf("Writing data to shared memory…\n");
strcpy(segptr,buff);
printf("DONE\n");
printf("Reading data from shared memory…\n");
printf("DATA:-%s\n",segptr);
printf("DONE\n");
printf("Removing shared memory Segment…\n");
if(shmctl(shmid,IPC_RMID,0)== -1)
printf("Can’t Remove Shared memory Segment…\n");
else
printf("Removed Successfully");
}
output:-
Image

IMPLEMENT DATA LINK LAYER FRAMING METHOD BIT STUFFING


IMPLEMENT DATA LINK LAYER FRAMING METHOD BIT STUFFING
import java.io.*;
public class bitst
{
public static void main(String args[]) throws IOException
{
int temp;
int data[]=new int[8];
int flag[]=new int[5];
int fdata[]=new int[25];
int fidata[]=new int[25];
DataInputStream obj= new DataInputStream(System.in);
System.out.println("Enter the Data Bits.....");
for (int i=0;i<8;i++)
{
data[i] = Integer.parseInt(obj.readLine());
}
System.out.println("Enter Flag Bits.....");
for (int i=0;i<5;i++)
{
flag[i] = Integer.parseInt(obj.readLine());
}
int idx=0;
for (int i=0;i<5;i++)
{
fdata[idx++] = flag[i];
}
for (int i=0;i<8;i++)
{
fdata[idx++] = data[i];
}
for (int i=0;i<5;i++)
{
fdata[idx++] = flag[i];
}
int fidx=0,count=0;
for(int i=0;i<idx;i++)
{
fidata[fidx++]=fdata[i];
if(fdata[i]==1)
count++;
else
count=0;
if(count==5)
{
fidata[fidx++]=0;
count=0;
}
}
System.out.print("Stuff Data : ");
for(int i=0;i<fidx;i++)
{
System.out.print(fidata[i]);
}
int k;
int mycount=0;
int mysecondcount=0;
int mydata[]=new int[25];
for(k=0;k<fidx;k++)
{
mydata[mysecondcount++]=fidata[k];
if(fidata[k]==1) 
mycount++;
else
mycount=0;
if(mycount==5)
{
mycount=0;
k++;
}
}
int j=mysecondcount;
System.out.println(" ");
System.out.print("Inverse : ");
for(int g=0;g<j;g++)
{
System.out.print(mydata[g]);
}
}
}
output:-
Image

IMPLEMENTING DINING PHILOSOPHER PROBLEM


C PROGRAM THAT IMPLEMENTS A  DINING PHILOSOPHER PROBLEM
#include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#define N 5
#define LEFT (i+4)%N
#define RIGHT (i+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2
sem_t spoon;
sem_t phil[N];
int state[N];
int phil_num[N]={0,1,2,3,4};
int fd[N][2];// file descriptors for pipes
pid_t pid, pids[N];// process ids
int i;int num;
void philosopher(int i);
void test(int i);
void take_spoon(int i);
void put_spoon(int i);
char buffer[100];
int main(void)
{
for(i=0;i<N;++i)
{
pipe(fd[i]);
pids[i]= fork();
printf("i=%d\n",i);
printf("pids[i]=%d\n",pids[i]);
if(pids[i]==0)
{// child
dup2(fd[i][1],1);
close(fd[i][0]);
close(fd[i][1]);
philosopher(i);
exit(0);
}
else
if(pids[i]>0)
{
// parent
dup2(fd[i][0],0);
close(fd[i][0]);
close(fd[i][1]);
}
}// wait for child processes to end
for(i=0;i<N;++i) 
waitpid(pids[i],NULL,0);
return 0;
}
void philosopher(int i)
{
while(1)
{
sleep(1);
take_spoon(i);
sleep(2);
put_spoon(i);
sleep(1);
}
}
void take_spoon(int i)
{
sem_wait(&spoon);
state[i]= HUNGRY;
printf("philosopher %d is hungry\n",i+1);
test(i);
sem_post(&spoon);
sem_wait(&phil[i]);
}
void put_spoon(int i)
{
sem_wait(&spoon);
state[i]= THINKING;
printf("philosopher %d puts down spoon %d and %d hin\n",i+1,LEFT+1,i+1);
printf("philosopher %d thinks\n",i+1);
test(LEFT);
test(RIGHT);
sem_post(&spoon);
}
void test(int i)
{
if( state[i]== HUNGRY && state[LEFT]!= EATING && state[RIGHT]!= EATING)
{
state[i]= EATING;
printf("philosopher %d takes spoon %d and %d\n",i+1,LEFT+1,i+1);
printf("philosopher %d eats\n",i+1);
sem_post(&phil[i]);
}
}
output:-
Screenshot-3

IMPLEMENTING PRODUCER-CONSUMER SYSTEM


C program that implements a producer-consumer system with two processes
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_BUFFER 3
int produceItem();
int child_pid;
int buffer[MAX_BUFFER],item;
int fillCount = 0; // items produced
int emptyCount = MAX_BUFFER; // remaining space
void producer()
{
while (1)
{
item = produceItem();
if(item==0)
return;
if(emptyCount==0)
{
printf("\nbuffer full");
break;
}
emptyCount--;
buffer[emptyCount]=item;
printf("\n %d put into the buffer..",item);
fillCount++;
}
return;
}
void consumer()
{
while (1)
{
if(fillCount==0)
{
printf("\nbuffer empty");
break;
}
fillCount--;
item=buffer[emptyCount];
printf("\n %d removed from buffer..",item);
emptyCount++;
printf("\n %d consumed..",item);
}
}
int produceItem()
{
int n;
printf("\n Enter the number for production (0 to stop)..\n");
scanf("%d",&n);
return n;
}
int main()
{
char i;
while(i!='y' && i!='Y')
{
producer();
consumer();
printf("\nDo you want to exit...(Y or N)....");
scanf("%c",&i);
}
}
output:-
Image

CREATION OF A CHILD PROCESS USING FORK SYSTEM CALL


C program that illustrates the creation of child process using fork system call:-
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{

        int i;
        printf("hello before fork \n");
        printf("i : %d\n",i);
        i=fork();
        printf("\n");
        if(i==0)
        {
                printf("Child has started\n\n");
                printf("child printing first time \n");
                printf("getpid : %d getppid : %d \n",getpid(),getppid());
                sleep(5);
                printf("\nchild printing second time \n");
                printf("getpid : %d getppid : %d \n",getpid(),getppid());
        }
        else
        {
                printf("parent has started\n");
                printf("getpid : %d  getppid : %d \n",getpid(),getppid());
                printf("\n");
        }
        printf("Hi after fork i : %d\n",i);
        return 0;
}
OUTPUT :-
Image

PROGRAMS FOR INFORMATION EXCHANGE BETWEEN CLIENT AND SERVER USING TCP AND UDP


TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}

output:-
Image


udpserver.java
import java.io.*;
import java.net.*;
class udpserver
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}

udpclient.java
import java.io.*;
import java.net.*;
class udpclient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
output:-
Image
...........................................................

SIMPLE NETWORK PROGRAMS


PROGRAM TO FIND IP-ADDRESS OF A COMPUTER:
import java.net.*;
class Inettest
{
    public static void main(String args[]) throws UnknownHostException
    {
        InetAddress Address=InetAddress.getLocalHost();
        System.out.println(Address);
        Address=InetAddress.getByName("www.sastra.edu");
        System.out.println(Address);
        InetAddress sw[]=InetAddress.getAllByName("www.google.com");
        for(int i=0;i<sw.length;i++)
            System.out.println(sw[i]);
    }
}

output:-
Image

Program for using Ping command:
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class pingip
{
  public static void runSystemCommand(String command){

        try {
            Process p = Runtime.getRuntime().exec(command);
            BufferedReader inputStream = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));

            String s = "";
            // reading output stream of the command
            while ((s = inputStream.readLine()) != null) {
                System.out.println(s);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
      
        String ip = "google.com";
        runSystemCommand("ping " + ip);

  
    }
}
output:-
Image

Program to send messages to other users in a network:-
import java.io.*;
  import java.net.*;
  class netsend{
   public static void main(String args[]) throws Exception
    {
    try{
        Runtime r=Runtime.getRuntime();
        Process p=null;
        String msg;
        String TRIP;
        String cmd;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter ip address of remote host");
        TRIP=br.readLine();
        System.out.println("Enter the msg to be sent to remote host");
        msg=br.readLine();
        cmd="net send"+TRIP+" "+msg;
        p=r.exec(cmd);
        Thread.sleep(1000);
        System.out.println("msg  sent to the sysytem");
        }catch(Exception e){
          System.out.println(e);
        }
      }

    }
output:-