Escolar Documentos
Profissional Documentos
Cultura Documentos
SYSTEMS
CPU SCHEDULING
Ex. No.: 1
DATE: 9 2 2012
Aim:
To write a java program to implement various CPU scheduling algorithms, such as FCFS,
SJF (Preemptive & non-preemptive), RoundRobin, and Priority (Preemptive & non-preemptive)
Algorithm:
Step 1: Get the number of processes from user.
Step 2: In main function get the choice
i.
ii.
iii.
iv. Calculate the turn around time of all the processes and the average
turn around time.
v. Display the Gantt Chart.
iv.
Get the CPU burst time and Priority for each process
ii.
iii.
Calculate the waiting time of all the processes and the average
waiting time.
iv.
Calculate the turn around time of all the processes and the average
turn around time.
v.
Get the CPU burst time, arrival time and Priority for each
process.
ii.
iii.
Calculate the waiting time of all the processes and the average
waiting time.
iv.
Calculate the turn around time of all the processes and the
average turn around time.
v.
PROGRAM:
/* rectangle.java */
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.lang.*;
/*
<applet code="rectangle" height=500 width=700>
</applet>
*/
public class rectangle_old extends Applet
{
int apw1[];
int p[];
int i=0,n,n1;
Graphics g= getGraphics();
public void init()
{
try
4
{
BufferedReader obj=new BufferedReader(new InputStreamReader
(System.in));
System.out.println("ENTER no. of processes:");
n=Integer.parseInt(obj.readLine());
int ch;
int bt[]=new int[n];
do {
System.out.println("MENU FOR CPU SCHEDULING");
System.out.println("1.FCFS \n 2.SHORTEST JOB FIRST (nonpreemptive) \n 3. SHORTEST JOB FIRST (preemptive) \n
4. ROUND ROBIN \n 5.PRIORITY (non-preemptive) \n
6. PRIORITY (preemptive) \n 7.EXIT \n");
System.out.println("ENTER YOUR CHOICE");
ch=Integer.parseInt(obj.readLine());
switch(ch)
{
case 1:
{
for( i=0;i<n;i++)
{
System.out.println("ENTER burst time for each
process: p"+(i+1));
bt[i]=Integer.parseInt(obj.readLine());
}
n1=n;
int turn[]=new int[n];
apw1=new int[n+1];
apw1[0]=0;
float t=0;
float tu=0;
5
p=new int[n];
for( i=1;i<=n;i++)
apw1[i]=bt[i-1]+apw1[i-1];
for( i=0;i<n;i++)
{
System.out.println("indivisual waiting time for
process p"+(i+1)+"is"+apw1[i]+" ");
}
for(i=0;i<n;i++)
{
p[i]=i+1;
System.out.print(p[i]);
}
for( i=0;i<n;i++)
t+=apw1[i];
float avg=t/n;
System.out.println("average waiting time is:"+avg);
for( i=0;i<n;i++)
{
turn[i]=bt[i]+apw1[i];
System.out.println("turnaround time for process p"+
(i+1)+"is"+turn[i]+" ");
}
for( i=0;i<n;i++)
tu+=turn[i];
float avg1=tu/n;
System.out.println("average turn-around time is:"+avg1);
paint(g);
}
break;
case 2:
6
{
for( i=0;i<n;i++)
{
System.out.println("Enter burst time for each
process:
p"+(i+1));
bt[i]=Integer.parseInt(obj.readLine());
}
n1=n;
int temp;
float t=0;
int turn[]=new int[n];
apw1=new int[n+1];
apw1[0]=0;
p=new int[n];
int sj[]=new int[n];
float tu=0;
for( i=0;i<n;i++)
sj[i]=bt[i];
for( i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(sj[i]>sj[j])
{
temp=sj[i];
sj[i]=sj[j];
sj[j]=temp;
}
for( i=0;i<n;i++)
for(int j=0;j<n;j++)
if(sj[i]==bt[j])
p[i]=j+1;
for(i=0;i<n;i++)
7
apw1[i+1]=sj[i]+apw1[i];
for( i=0;i<n;i++)
{
System.out.println("individual waiting time for process p"+p[i]
+"is"+apw1[i]+" ");
}
for( i=0;i<n;i++)
t+=apw1[i];
float avg=t/n;
System.out.println("average waiting time is:"+avg);
for( i=0;i<n;i++)
{
int k=p[i];
turn[i]=bt[k-1]+apw1[i];
System.out.println("turnaround time for process p"+p[i]
+"is"+turn[i]+" ");
}
for( i=0;i<n;i++)
tu+=turn[i];
float avg1=tu/n;
System.out.println("average turn-around time is:"+avg1);
paint(g);
}
break;
case 3:
{
int total=0,k=0,co=0,small=999,sp=0,sp1=0,x=0,count=0;
int pro[][]=new int[n][3];
int wt[]=new int[n];
int wt1[]=new int[n];
int bt1[]=new int[n];
8
{
if(small>pro[j][1]&&pro[j][1]!=0)
{
small=pro[j][1];
sp=pro[j][0];
sp1=j;
}
}
if(p[x]==sp)
{
apw1[x+1]++;
}
else
{
x++;
p[x]=sp;
apw1[x+1]=apw1[x];
apw1[x+1]++;
count++;
}
pro[sp1][1]-=1;
if(pro[sp1][1]==0)
tt[sp1]=i;
for(int j=0;j<n;j++)
{
if(pro[j][1]!=0&&j!=sp)
wt[j]+=1;
}
k++;
}
10
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(pro[i][0]>pro[j][0])
{
int temp[]=pro[i];
System.out.println();
for(int m=0;m<=count;m++)
p[m]+=1;
double awt=0.0,att=0.0;
System.out.println();
for (int i = 0; i<n;i++)
{
System.out.println("waiting time for process p
"+i+" "+(wt[i]-wt1[i]));
awt+=(wt[i]-wt1[i]);
att+=(wt[i]-wt1[i]+bt1[i]);
}
for (int i = 0; i<n;i++)
{
System.out.println("turnaround time for
process p"+i+" "+(wt[i]-wt1[i]+bt1[i]));
}
System.out.println("Average waiting time : "+
(awt/n));
System.out.println("Average turnaround time : "+
(att/n));
n1=count+1;
paint(g);
}
break;
case 4:
11
{
for( i=0;i<n;i++)
{
System.out.println("ENTER burst time for each
process: p"+(i+1));
bt[i]=Integer.parseInt(obj.readLine());
}
int ro[]=new int[n];
apw1=new int[20];
apw1[0]=0;
int sq[]=new int[20];
int temp;
float t=0;
float tu=0;
int apw[]=new int[n];
int bttime=0;
int turn[]=new int[n];
int f=0;
for(i=0;i<n;i++)
{
ro[i]=bt[i];
}
p=new int[30];
System.out.println("enter time quantum");
int ts=Integer.parseInt(obj.readLine());
int k=0;
sq[k]=0;
i=0;
temp=ts;
int count=0;
do
12
{
if(ro[i]==0)
{
i++;
sq[k]=sq[k-1]+temp;
}
else
if(ro[i]>=ts)
{
ro[i]=ro[i]-ts;
p[k]=i+1;
k++;
i++;
temp=ts;
sq[k]=sq[k-1]+temp;
turn[i-1]=sq[k];
f=0;
for(int m=0;m<n;m++)
f+=ro[m];
count++;
}
else
if(ro[i]>0)
{
temp=ro[i];
ro[i]=0;
p[k]=i+1;
i++;
k++;
sq[k]=sq[k-1]+temp;
turn[i-1]=sq[k];
13
f=0;
for(int m=0;m<n;m++)
f+=ro[m];
count++;
}
if(i==n)
i=0;
}while(f!=0);
System.out.println();
for(i=0;i<=count;i++)
{
apw1[i]=sq[i];
}
System.out.println();
for(i=0;i<n;i++)
{
apw[i]=turn[i]-bt[i];
t+=apw[i];
tu+=turn[i];
}
for(i=0;i<n;i++)
System.out.println(" waiting time for p"+(i+1)+"is:"+apw[i]);
float avg=t/n;
System.out.println("average waiting time is:"+avg);
for(i=0;i<n;i++)
System.out.println("turn around time is:"+turn[i]);
float avg1=tu/n;
System.out.println("average turn-around time is:"+avg1);
n1=count;
paint(g);
}
14
break;
case 5:
{
for( i=0;i<n;i++)
{
System.out.println("Enter burst time for each process:
p"+(i+1));
bt[i]=Integer.parseInt(obj.readLine());
}
n1=n;
int pr[]=new int[n];
int pr1[]=new int[n];
float t=0;
int temp;
int turn[]=new int[n];
p=new int[n];
apw1=new int[n+1];
apw1[0]=0;
float tu=0;
for(i=0;i<n;i++)
{
System.out.println("Enter the priority for p"+(i+1));
pr[i]=Integer.parseInt(obj.readLine());
}
for(i=0;i<n;i++)
{
pr1[i]=pr[i];
}
for( i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(pr1[i]>pr1[j])
15
{
temp=pr1[i];
pr1[i]=pr1[j];
pr1[j]=temp;
}
for( i=0;i<n;i++)
for(int j=0;j<n;j++)
if(pr1[i]==pr[j])
p[i]=j+1;
for(i=0;i<n;i++)
{
int k=p[i];
apw1[i+1]=bt[k-1]+apw1[i];
}
for( i=0;i<n;i++)
{
System.out.println("individual waiting time for
process p"+p[i]+"is"+apw1[i]+" ");
}
for( i=0;i<n;i++)
t+=apw1[i];
float avg=t/n;
System.out.println("average waiting time is:"+avg);
for( i=0;i<n;i++)
{
int k=p[i];
turn[i]=bt[k-1]+apw1[i];
System.out.println("turnaround time for process
p"+p[i]+"is"+turn[i]+" ");
}
for( i=0;i<n;i++)
16
tu+=turn[i];
float avg1=tu/n;
System.out.println("average turn-around time is:"+avg1);
paint(g);
}
break;
case 6:
{
int total=0,k=0,co=0,small=999,sp=0,sp1=0,x=0,count=0;
int pro[][]=new int[n][4];
int wt[]=new int[n];
int wt1[]=new int[n];
int bt1[]=new int[n];
int tt[]=new int[n];
apw1=new int [20];
p=new int[20];
for(int i=0;i<n;i++)
{
pro[i][0]=i;
System.out.print("Burst Time for P"+i+" :");
pro[i][3]=Integer.parseInt(obj.readLine());
total+=pro[i][3];
System.out.print("Arrival Time for P"+i+" :");
pro[i][2]=Integer.parseInt(obj.readLine());
System.out.print("Priority for P"+i+" :");
pro[i][1]=Integer.parseInt(obj.readLine());
}
for(int i=0;i<n;i++)
wt1[i]=pro[i][2];
for(int i=0;i<n;i++)
bt1[i]=pro[i][3];
17
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(pro[i][2]>pro[j][2])
{
int temp[]=pro[i];
pro[i]=pro[j];
pro[j]=temp;
}
for(int i=1;i<=total;i++)
{
small=999;
for(int j=co;j<n;j++)
if(k>=pro[j][2])
co++;
for(int j=0;j<co;j++)
{
if(small>pro[j][1]&&pro[j][3]!=0)
{
small=pro[j][1];
sp=pro[j][0];
sp1=j;
}
}
if(p[x]==sp)
{
apw1[x+1]++;
}
else
{
x++;
p[x]=sp;
18
apw1[x+1]=apw1[x];
apw1[x+1]++;
count++;
}
pro[sp1][3]-=1;
if(pro[sp1][3]==0)
tt[sp1]=i;
for(int j=0;j<n;j++)
{
if(pro[j][3]!=0&&j!=sp)
wt[j]+=1;
}
k++;
}
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(pro[i][0]>pro[j][0])
{
int temp[]=pro[i];
pro[i]=pro[j];
pro[j]=temp;
int tem=wt[i],tem1=tt[i];
wt[i]=wt[j];
wt[j]=tem;
tt[i]=tt[j];
tt[j]=tem1;
}
System.out.println();
for(int m=0;m<=count;m++)
p[m]+=1;
double awt=0.0,att=0.0;
19
System.out.println();
for (int i = 0; i<n; i++)
{
System.out.println("waiting time for process p "+i+" "+
(wt[i]-wt1[i]));
awt+=(wt[i]-wt1[i]);
att+=(wt[i]-wt1[i]+bt1[i]);
}
for (int i = 0; i<n; i++)
{
System.out.println("turnaround time for process p"+i+" "+
(wt[i]-wt1[i]+bt1[i]));
}
System.out.println("Average waiting time : "+(awt/n));
System.out.println("Average turnaround time : "+(att/n));
n1=count+1;
paint(g);
}}
} while(ch!=7);
}
catch (Exception e)
{}
}
public void paint(Graphics g)
{
for(int j=1;j<=n1;j++)
{
g.drawRect(50,50,(apw1[j]*20),30);
g.drawString("p"+p[j-1],(55+(apw1[j-1]*20)),70);
g.drawString(""+apw1[j-1],50+(apw1[j-1]*20),100);
}
20
g.drawString(""+apw1[n1],50+(apw1[n1]*20),100);
}
}
Applet Viewer : rectangle.html
<html>
<applet code="rectangle_old.class" height=500 width=700>
</applet>
</html>
OUTPUT:
Z:\OS\labpgm>appletviewer rectangle_old.html
ENTER no. of processes:
5
MENU FOR CPU SCHEDULING
1. FCFS method
2. SHORTEST JOB FIRST method (non-preemptive)
3. SHORTEST JOB FIRST method (preemptive)
4. ROUND ROBIN method
5. PRIORITY method (non-preemptive)
6. PRIORITY method (preemptive)
7. EXIT
ENTER YOUR CHOICE
1 individual
ENTER burst time for each process: p1
1.FCFS method
2.SHORTEST JOB FIRST method(non-preemptive)
3.SHORTEST JOB FIRST method(preemptive)
4.ROUND ROBIN method
5.PRIORITY method (non-preemptive)
6.PRIORITY method (preemptive)
7.EXIT
ENTER YOUR CHOICE
25
28
RESULT:
Thus the java program to implement various CPU scheduling algorithms was
written and executed successfully.
Ex.No: 2
DATE: 16 2 2012
AIM:
To write a java program to implement various memory allocation schemes (First Fit, Best
Fit and Worst Fit)
PROBLEM DESCRIPTION:
The memory is divided into many partitions. When a partition is free, a process is selected
form the input queue and is loaded into the free partition. When the process terminates the partition
is available for another process
Initially, all memory is available for user processes, and it considers the available block of
memory, a hole. When a process arrives and needs memory, we search for a hole large enough for
the process. If we found one, we allocate only as much memory as is needed, keeping the rest
available to satisfy the future request.
The set of holes is searched to determine which hole is the best to allocate. The following
strategies are used to select a free hole from the set of available holes:
First fit: Allocate the first hole that is big enough. Searching can start at the beginning if set of
holes or where the first fit search ended. We can stop as soon as we find a free hole that is large
enough.
Best fit: Allocate the smallest hole that is big enough. We must search the entire list, unless the list
is kept ordered by size. This strategy produces the smallest leftover hole
Worst fit: Allocate the largest hole. Again we must search the entire list, unless it is sorted by size.
This strategy produces the largest leftover hole, which may be more useful than the smaller
leftover hole from a best-fit approach
ALGORITHM:
29
Step 1: Import all the necessary files and declare the required variables.
Step 2: Get the memory block size, whether the block is used (1) or free (0) and process size
from the user.
Step 3: Select the algorithm based on the choice from the user using switch case.
Step 4: For the First Fit Algorithm, find the first memory partition which is big enough to hold
that process and allocate the memory partition to that process. Also calculate the free
memory space.
Step 5: For the Best Fit Algorithm, find the smallest memory partition which is big enough to
hold the requesting process and allocate the memory partition to the process and
calculate the free memory space.
Step 6: For the Worst Fit Algorithm, find the largest available memory partition which is big
enough to hold the requesting process and allocate the memory partition to the
process and calculate the free memory space.
Step 7: Display the final frame size and allocated process details and free memory space.
Step 8: Terminate the program
PROGRAM:
import java.io.*;
public class Fitting
{
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
int process[], rprocess[], block[], rblock[], usage[], rusage[];
int p, b, free, used, rfree, rused, c, c1;
public Fitting() throws IOException
{
System.out.println("Enter number of blocks");
b=Integer.parseInt(input.readLine());
System.out.println("Enter number of processes");
p=Integer.parseInt(input.readLine());
process=new int[p];
30
rprocess=new int[p];
block=new int[b];
rblock=new int[b];
usage=new int[b];
rusage=new int[b];
c=0;
}
void read() throws IOException
{
int i;
System.out.println("Enter block sizes");
for(i=0;i<b;i++)
{
System.out.print("Block "+(i+1)+" : ");
rblock[i]=Integer.parseInt(input.readLine());
}
System.out.println("Enter block usage scenario");
for(i=0;i<b;i++)
{
System.out.println("Is block "+(i+1)+" used (1) or free
(0)?");
rusage[i]=Integer.parseInt(input.readLine());
if(rusage[i]==1)
{
rused=rused+rblock[i];
c1++;
}
else
rfree=rfree+rblock[i];
}
System.out.println("Enter process demand");
31
for(i=0;i<p;i++)
{
System.out.print("Process "+(i+1)+" : ");
rprocess[i]=Integer.parseInt(input.readLine());
}
}
void reset()
{
int i;
for(i=0;i<b;i++)
{
block[i]=rblock[i];
usage[i]=rusage[i];
}
for(i=0;i<p;i++)
process[i]=rprocess[i];
used=rused;
free=rfree;
c=c1;
}
void display()
{
int total;
total=rused+rfree;
System.out.println("Blocks used = "+c);
System.out.println("Total used space = "+used);
System.out.println("Blocks free = "+(b-c));
System.out.println("Total free space = "+(total-used));
}
void f_fit()
{
32
int i,j;
for(i=0;i<p;i++) //Processes.
for(j=0;j<b;j++) //Blocks.
{
if(process[i]<=block[j]&&usage[j]==0)
{
usage[j]=1;
used=used+block[j];
c++;
System.out.println("Process "+(i+1)+" is in block "+
(j+1));
break;
}
}
}
void b_fit()
{
int i,j,size,best;
for(i=0;i<p;i++)
{
size=32967;
best=-1;
for(j=0;j<b;j++)
{
if(process[i]<=block[j]&&usage[j]==0&&(block[j]process[i])<size)
{
size=block[j]-process[i];
best=j;
}
}
33
(best+1));
}
}
}
void w_fit()
{
int i,j,size,worst;
for(i=0;i<p;i++)
{
size=0;
worst=-1;
for(j=0;j<b;j++)
{
if(process[i]<=block[j]&&usage[j]==0&&(bl
ock[j]-process[i])>size)
{
size=block[j]-process[i];
worst=j;
}
}
if(worst!=-1) //Ensuring a worst fit.
{
usage[worst]=1;
used=used+block[worst];
c++;
34
System.out.println("Process
(worst+1));
}
}
}
public static void main(String[] args) throws IOException
{
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
int option;
String choice;
Fitting f=new Fitting();
f.read();
do
{
f.reset();
System.out.println("Menu");
System.out.println("1. First fit");
System.out.println("2. Best fit");
System.out.println("3. Worst fit");
System.out.println("4. Block information");
System.out.println("Enter option");
option=Integer.parseInt(input.readLine());
switch(option)
{
case 1: f.f_fit();
break;
case 2: f.b_fit();
break;
case 3: f.w_fit();
break;
case 4: f.display();
35
break;
default: System.out.println("Invalid input");
}
f.display();
System.out.println("Press Y to continue");
choice=input.readLine();
}
while(choice.compareToIgnoreCase("y")==0);
}
}
OUTPUT:
Z:\>javac Fitting.java
Z:\>java Fitting
Enter number of blocks
5
Enter number of processes
4
Enter block sizes
Block 1 : 100
Block 2 : 500
Block 3 : 200
Block 4 : 300
Block 5 : 600
Enter block usage scenario
Is block 1 used (1) or free (0)?
0
Is block 2 used (1) or free (0)?
0
Is block 3 used (1) or free (0)?
0
36
2
Process 1 is in block 4
Process 2 is in block 2
Process 3 is in block 3
Process 4 is in block 5
Blocks used = 4
Total used space = 1600
Blocks free = 1
Total free space = 100
Press Y to continue
y
Menu
1. First fit
2. Best fit
3. Worst fit
4. Block information
Enter option
3
Process 1 is in block 5
Process 2 is in block 2
Process 3 is in block 4
Blocks used = 3
Total used space = 1400
Blocks free = 2
Total free space = 300
Press Y to continue
y
Menu
1. First fit
2. Best fit
3. Worst fit
38
4. Block information
Enter option
4
Blocks used = 0
Total used space = 0
Blocks free = 5
Total free space = 1700
Blocks used = 0
Total used space = 0
Blocks free = 5
Total free space = 1700
Press Y to continue
39
RESULT:
Thus the java program for implementing various memory allocation schemes (First Fit,
Best Fit and Worst Fit) was executed and the output was verified.
Ex. No.:3
DATE: 23 2 2012
AIM:
To write a java program to implement Bankers algorithm for deadlock avoidance.
PROBLEM STATEMENT:
The Banker's algorithm is run by the operating system whenever a process requests
resources. The algorithm avoids deadlock by denying or postponing the request if it determines
that accepting the request could put the system in an unsafe state (one where deadlock could
occur). When a new process enters a system, it must declare the maximum number of instances of
each resource type that may not exceed the total number of resources in the system. Also, when a
process gets all its requested resources it must return them in a finite amount of time.
Let n be the number of processes in the system and m be the number of resource types.
Then the following data structures are needed:
Available: A vector of length m indicates the number of available resources of each type. If
Available[j] = k, there are k instances of resource type Rj available.
Max: An nm matrix defines the maximum demand of each process. If Max[i,j] = k, then
Pi may request at most k instances of resource type Rj.
Need: An nm matrix indicates the remaining resource need of each process. If Need[i,j] =
k, then Pi may need k more instances of resource type Rj to complete task.
Step 1: Import all the java files and declare the necessary variables.
Step 2:A process P makes a request for resources.
Step 3: If Request<=Need, then allocate the resource for the particular process,
otherwise goto step 3
Step 4: If Request <= Available, then goto step 4 otherwise suspend the particular
process
Step 5: Pretend to allocate requested resources
System.out.print("\t");
p[i]=Integer.parseInt(br.readLine());
}
System.out.println("Enter the no. of resources");
n=Integer.parseInt(br.readLine());
System.out.println("Enter the details of allocatedresources");
for(i=0;i<m;i++)
{
System.out.print("Enter the allocated resource for the process:" +i);
System.out.println("\n");
for(j=0;j<n;j++)
alloc[i][j]=Integer.parseInt(br.readLine());
System.out.print("\n");
}
System.out.println("Enter the details of max.resources");
for(i=0;i<m;i++)
{
System.out.println("Enter the max.resources for the process" +i);
for(j=0;j<n;j++)
{
max[i][j]=Integer.parseInt(br.readLine());
}
System.out.print("\n");
}
System.out.println("Enter the details of available resources");
for(i=0;i<n;i++)
{
System.out.print("\t");
avl[i]=Integer.parseInt(br.readLine());
}
for(i=0;i<m;i++)
42
{
for(j=0;j<n;j++)
{
if(max[i][j]>0)
{
need[i][j]=max[i][j]-alloc[i][j];
}
}
}
System.out.println(" The details of max. need of processes");
for(i=0;i<m;i++)
{
System.out.print("Enter the max need resource for the process:" +i);
for(j=0;j<n;j++)
{
System.out.print(need[i][j]);
System.out.print("\t");
}
System.out.print("\n");
}
//System.out.println(" The safe sequence is");
safe(p,alloc,need,avl,m,n);
}
public static void safe(int p[],int alloc[][],int need[][],int avl[],int m,int n)
{
int i,j,c=0,f=0,k=0,f1=0;
int[] np=new int[7];
int[] ss=new int[15];
for(i=0;i<m;i++)
{
f=0;
43
for(j=0;j<n;j++)
{
if(need[i][j]<=avl[j])
{
f++;
}
}
System.out.println("test "+ f);
if(f==n)
{
System.out.println("Allocated " +p[i]);
ss[i]=1;
System.out.println(" before Allocation ");
for(j=0;j<n;j++)
{
System.out.print(avl[j]);
System.out.println("\t");
}
System.out.println("Modified Avl");
for(j=0;j<n;j++)
{
avl[j]=alloc[i][j]+avl[j];
System.out.print(avl[j]);
System.out.println("\t");
}
}
else
{
ss[i]=999;
}
}
44
for(i=0;i<m;i++)
{
if(ss[i]==999)
{
f1++;
for(j=0;j<n;j++)
{
np[k]=p[i];
System.out.println("unallocated process "+ np[k]);
}
k++;
}
else
{
System.out.print("\t");
}
}
if(f1!=0)
{
safe1(np,alloc,need,avl,m,n);
}
}
public static void safe1(int[] np,int[][] alloc,int need[][],int avl[],int m,int n)
{
int i1,j1,c1=0,f1=0,k1=0,f2=0,x=0;
int[] np1=new int[7];
int[] ss=new int[15];
for(i1=0;i1<m;i1++)
{
if(np[x]==i1)
{
45
f1=0;
for(j1=0;j1<n;j1++)
{
if(need[i1][j1]<=avl[j1])
{
f1++;
//System.out.println(" re test "+ f1);
}
}
if(f1==n)
{
System.out.println("Allocated process " +i1);
System.out.println("before Modification");
for(j1=0;j1<n;j1++)
{
System.out.print(avl[j1]);
System.out.println("\t");
}
ss[i1]=1;
System.out.println("Modified Avl");
for(j1=0;j1<n;j1++)
{
avl[j1]=alloc[i1][j1]+avl[j1];
System.out.print(avl[j1]);
System.out.println("\t");
}
}
else
{
ss[i1]=999;
46
OUTPUT:
Z:\OS>javac bbanker.java
Z:\OS>java bbanker
Enter the no. of processes
5
47
0 7
Allocated 0
before Allocation
1
5
2
2
Modified Avl
1
5
3
3
Allocated 2
Before Allocation
1
5
3
3
Modified Avl
2
8
8
4
Allocated 3
before Allocation
49
2
8
8
4
Modified Avl
2
13
11
5
unallocated process 1
unallocated process 1
unallocated process 1
unallocated process 1
unallocated process 4
unallocated process 4
unallocated process 4
unallocated process 4
Allocated process 1
before Modification
2
13
11
5
Modified Avl
3
13
11
6
Unallocated processes4
The system is in unsafe state
50
RESULT:
Thus the java program for the implementation of Bankers Algorithm for deadlock
avoidance was successfully executed and output was verified.
Ex.No: 4
Date: 1 3 2012
AIM:
To write a java program to implement various Page Replacement Algorithms (FIFO, LRU,
and Optimal).
PROBLEM STATEMENT:
Page replacement algorithms decide which memory pages to page out (swap out, write to
disk) when a page of memory needs to be allocated. Paging happens when a page fault occurs and
a free page cannot be used to satisfy the allocation, either because there are none, or because the
number of free pages is lower than some threshold.When the page that was selected for
replacement and paged out is referenced again it has to be paged in (read in from disk), and this
involves waiting for I/O completion. This determines the quality of the page replacement
algorithm. Algorithms are
FIFO
LRU
OPTIMAL
FIFO:
On a page fault, evict the page that has been in the cache for the longest time.The first-in,
first-out (FIFO) page replacement algorithm is a low-overhead algorithm.
LRU:
When a page fault occurs, throw out the page that has been unused for the longest time.
This strategy is called LRU (Least Recently Used) paging.
OPTIMAL:
Each page can be labeled with the number of instructions that will be executed before that
page is first referenced.This algorithm simply says that the page with the highest label should be
removed.
51
ALGORITHM:
Step 1: Import all the required java files.
Step 2: Create a main class called Paging and initialize all the variables
(n,page[],f,frames[],faults,count).
Step 3: Create a function Paging().Get the Number of pages and assign it to n. Then, get
number of page frames and assign it to f.
Step 4: Create a function reset().Declare a variable j.Assign Page fault to be 0. And each frame
size to be zero. Create a function read().Get size of each page.
Step 5:In main function,get the choice.
(a)If the choice is 1, Call FIFO function, replace the page which longly existed.
(b)If the choice is 2, Call LRU function, replace the page which longly unused.
(c)If the choice is 3, Call OPT function, replace the page whice has highest Label.
Step 6: Display the Pages
Step 7: End the program.
PROGRAM:
import java.io.*;
public class Paging
{
BufferedReader input=new BufferedReader(newInputStreamReader(System.in));
int n, page[], f, frames[], faults, count;
double rate;
public Paging() throws IOException
{
System.out.println("Enter number of pages");
n=Integer.parseInt(input.readLine());
page=new int[n];
System.out.println("Enter number of page frames");
f=Integer.parseInt(input.readLine());
frames=new int[f];
count=1;
52
}
void reset()
{
int j;
for(j=0;j<f;j++)
frames[j]=0;
faults=0;
count=1;
}
void read() throws IOException
{
int i;
System.out.println("Enter the pages");
for(i=0;i<n;i++)
{
System.out.println("Enter page number "+(i+1));
page[i]=Integer.parseInt(input.readLine());
}
for(i=0;i<f;i++)
frames[i]=-1;
}
void fifo()
{
int i,j,k=0;
reset();
boolean found=false;
for(i=0;i<n;i++)
{
for(j=0;j<f;j++)
{
if(page[i]==frames[j])
53
found=true;
}
if(found==false)
{
frames[k]=page[i];
if(k==f-1)
k=0;
else
k++;
faults++;
}
display();
found=false;
}
System.out.println("Number of page faults = "+faults);
System.out.println("Fault rate = "+(faults*1.0/n));
}
void lru()
{
int i,j,duration[],max;
reset();
duration=new int[f];
boolean found=false;
for(i=0;i<n;i++)
{
for(j=0;j<f;j++)
duration[j]++;
for(j=0;j<f;j++)
{
if(page[i]==frames[j])
{
54
found=true;
duration[j]=0;
}
}
if(found==false)
{
max=0;
for(j=0;j<f;j++)
{
if(duration[j]>duration[max])
max=j;
}
frames[max]=page[i];
duration[max]=0;
faults++;
}
display();
found=false;
}
System.out.println("Number of page faults="+faults);
System.out.println("Fault rate = "+(faults*1.0/n));
}
void opt()
{
int i,j=0,k,duration[],max,flag[];
reset();
duration=new int[f];
flag=new int[f];
boolean found=false;
for(i=0;i<n;i++)
{
55
for(j=0;j<f;j++)
{
flag[j]=0;
duration[j]=n;
}
for(k=i+1;k<n;k++)
{
for(j=0;j<f;j++)
if(page[k]==frames[j]&&flag[j]==0)
{
duration[j]=k;
flag[j]=1;
}
}
for(j=0;j<f;j++)
if(page[i]==frames[j])
found=true;
if(found==false)
{
max=0;
for(j=0;j<f;j++)
{
if(duration[j]>duration[max])
max=j;
if(frames[j]<0)
{
max=j;
break;
}
}
frames[max]=page[i];
56
faults++;
}
display();
found=false;
}
System.out.println("Number of page faults = "+faults);
System.out.println("Fault rate = "+(faults*1.0/n));
}
void display()
{
int i;
System.out.print("Page frame "+count+" :");
for(i=0;i<f;i++)
{
if(frames[i]==-1)
System.out.print(" -");
else
System.out.print(" "+frames[i]);
}
System.out.print("\n");
count++;
}
public static void main(String[] args) throws IOException
{
int option;
String choice;
Paging p=new Paging();
p.read();
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
do
{
57
System.out.println("Menu");
System.out.println("1. FIFO");
System.out.println("2. LRU");
System.out.println("3. OPT");
System.out.println("Enter option");
option=Integer.parseInt(input.readLine());
switch(option)
{
case 1: p.fifo();
break;
case 2: p.lru();
break;
case 3: p.opt();
break;
default: System.out.println("Invalid input");
}
System.out.println("Press Y to continue");
choice=input.readLine();
}
while(choice.compareToIgnoreCase("y")==0);
// TODO Auto-generated method stub
}
OUTPUT:
Z:\OS>javac Paging.java
Z:\OS>java Paging
Enter number of pages
Page frame 1 : 1 0 0
Page frame 2 : 1 3 0
Page frame 3 : 1 3 2
Page frame 4 : 1 3 2
Page frame 5 : 1 3 2
Number of page faults = 3
Fault rate = 0.6
Press Y to continue
y
Menu
1. FIFO
2. LRU
3. OPT
Enter option
3
Page frame 1 : 1 0 0
Page frame 2 : 1 3 0
Page frame 3 : 1 3 2
Page frame 4 : 1 3 2
Page frame 5 : 1 3 2
Number of page faults = 3
Fault rate = 0.6
Press Y to continue
RESULT:
60
Thus the program for implementation of Page replacement alogorithms (FIFO, LRU, AND
Optimal) was written and executed.
MULTIIPROCESSOR
OPERATING SYSTEMS
61
PROCESS SYNCHRONIZATION
Ex.No: 5
DATE: 8 3 2012
USING SEMAPHORES
AIM:
To write a java program to implement process synchronization using semaphores.
PROBLEM STATEMENT:
Assume there are three processes: Pa, Pb, and Pc. Only Pa can output the letter A,
Pb B, and Pc C. Utilizing only semaphores (and no other variables) the processes are
synchronized so that the output satisfies the following conditions:
a) A B must be output before any C's can be output.
b) B's and C's must alternate in the output string, that is, after the first B is
output, another B cannot be output until a C is output.
Similarly, once a C is output, another C cannot be output until a B is output.
c) The total number of B's and C's which has been output at any given point
in the output.
String cannot exceed the number of A's which have been output up to that point.
ALGORITHM:
Step 1: Import all the required java files.
Step 2: Create a class process and initialize all the variables (count, pacount, pbcount).
Step 3: First initialize the count for all the process as 0, increment the count for process
A first and then output the process A,
Step 4: After printing process A, check the condition that the count of process A is
greater than the count of process B then increment the count as 1 and ouput
the process B and then output process C.
Step 5: Create a main class called Semaphore and create objects for process, with that
62
object call all the process function one by one and by checking one by one.
Step 6: End the program.
PROGRAM:
import java.io.*;
import java.util.Random;
class Proces
{
public int count=0;
public String cs;
public Proces(String val)
{
cs=val;
}
public String acquire()
{
System.out.print(cs);
count++;
return(cs);
}
public int getcount()
{
return(count);
}
}
class Semaphore
{
public static void main(String[] args)throws IOException
{
int ca,cb,cc,count=0,s=1,j=0;
Random r=new Random();
63
int n=r.nextInt(10);
int m=r.nextInt(5);
String item[]=new String[50]; //item[] holds character being printed
Proces a=new Proces("A"); //Process A
Proces b=new Proces("B"); //Process B
Proces c=new Proces("C"); //Process C
for(int i=1;i<=n;i++)
{
if(s==1)
{
s=0;
for(int k=1;k<=m;k++)
item[++j]=a.acquire();
}
ca=a.getcount();
s++;
if(s==1)
{
s=0;
if((item[j]=="A")||(item[j]=="C"))
item[++j]=b.acquire();
}
cb=b.getcount();
s++;
if(s==1)
{
s=0;
if(item[j]=="B")
item[++j]=c.acquire();
}
cc=c.getcount();
64
s++;
count=cb+cc;
if(ca<=count)
{
if(s==1)
{
s=0;
item[++j]=a.acquire();
}
}
ca=a.getcount();
s++;
}
}
}
OUTPUT:
Z:\OS>javac Semaphore.java
Z:\OS>java Semaphore
A
A
B
C
A
A
Z:\OS>javac Semaphore.java
Z:\OS>java Semaphore
A
B
65
RESULT:
Thus the program for implementing process synchronization using semaphores was
executed and output was verified.
Ex.No: 6
DATE: 15 3 2012
AIM:
To write a java program to implement the cigarette smoker problem using multithreading.
PROBLEM STATEMENT:
Consider a simulation with three smoker threads and one agent thread each smoker
continuously makes a cigarette and smokes it. But to makes a cigarette a smoker and matches, each
one having only one ingredient out of three. The three smoker threads are initially blocked.
The agent places two randomly chosen ingredients and unblocks one smoker who has the
remaining ingredients. The agent blocks and then the smoker can make cigarette and smokes it for
a random amount of time. Unblocking the agent on completion of smoking the cigarette the agent
then puts out another two of the ingredients and the cycle repeats.
ALGORITHM:
Step 1: Import all the java files.
Step 2: Create a class cigarette and initialize all the variables and ingredients.
Step 3: Create a thread and check the ingredients for all smoker to smoke.
Step 4: Then create an agent class for providing all the ingredients by extending the
thread class.
Step 5: After checking the conditions in agent class then the Agent will provide
ingredients. The smoker will use that (two out of three) and roll the cigarette and starts
smoking.
Step 6: Repeat this until all the smoker will starts smoking by getting all the ingredients.
PROGRAM:
66
import java.util.*;
public class Cigarette {
public class Table {
public static final int Nothing = 0;
public static final int Tobacco = 1;
public static final int Paper = 2;
public static final int Matches = 4;
public static final int Tobacco_Paper = Tobacco + Paper;
public static final int Paper_Matches = Paper + Matches;
public static final int Matches_Tobacco = Matches + Tobacco;
public static final int Everything = Tobacco + Paper + Matches;
private int contains;
public Table () {
contains = Nothing;
}
public synchronized void Put(int what) {
System.out.println(Thread.currentThread().getName() +
": putting "+Contains(what));
contains = contains | what;
notifyAll();
try {
wait();
} catch (InterruptedException e) {}
}
public synchronized void Get(int what) {
while ((contains & what) != what) {
try {
//System.out.println(Thread.currentThread().getName() +
// ": Getting " + Contains(what) + " - No!");
wait();
} catch (InterruptedException e) {}
67
}
System.out.println(Thread.currentThread().getName() +
": Getting " + Contains(what) + " - Yes!");
contains = contains ^ what;//initializes contains=0
}
public synchronized void DoneSmoking() {
notifyAll();
}
public String Contains(int what) {
String s = "";
if ((what & Tobacco) == Tobacco)
s = s + "tobacco ";
if ((what & Paper) == Paper)
s = s + "paper ";
if ((what & Matches) == Matches)
s = s + "matches ";
return s;
}
}
public class Agent extends Thread {
private Table table;
private Random rand;
public Agent(Table tab, String name) {
super (name);
table = tab;
rand = new Random();
}
public void run() {
while (true) {
switch (Math.abs(rand.nextInt()) % 3) {
68
case 0:
table.Put(Table.Tobacco_Paper);
break;
case 1:
table.Put(Table.Paper_Matches);
break;
case 2:
table.Put(Table.Matches_Tobacco);
break;
}
}
}
}
public class Smoker extends Thread {
private Table table;
private Random rand;
private int needs;
public Smoker(Table tab, String name, int what) {
super (name);
table = tab;
rand = new Random();
needs = Table.Everything ^ what;
}
public void run() {
while (true) {
try {
table.Get(needs);
System.out.println(getName() + ": I got what I needed!");
System.out.println(getName() + ": Rolling.");
sleep(Math.abs(rand.nextInt()) % 1000);
System.out.println(getName() + ": Smoking.");
69
sleep(Math.abs(rand.nextInt()) % 1000);
System.out.println(getName() + ": Done smoking.");
table.DoneSmoking();
}
catch (InterruptedException e) {}
}
}
}
public void mainRun(String[] args) {
Smoker smo1, smo2, smo3;
Agent agent;
Table table;
table = new Table();
agent = new Agent(table, "Agent");
smo1 = new Smoker(table, " Smoker 1", Table.Paper);
smo2 = new Smoker(table, " Smoker 2", Table.Matches);
smo3 = new Smoker(table, " Smoker 3", Table.Tobacco);
agent.start();
smo1.start();
smo2.start();
smo3.start();
}
public static void main(String[] arg)
{
Cigarette a = new Cigarette();
a.mainRun(arg);
}
}
70
OUTPUT:
Z:\OS>javac cigarette.java
Z:\OS>java cigarette
Agent: putting paper matches
Smoker 3: Getting paper matches - Yes!
Smoker 3: I got what I needed!
Smoker 3: Rolling.
Smoker 3: Smoking.
Smoker 3: Done smoking.
Agent: putting paper matches
Smoker 3: Getting paper matches - Yes!
Smoker 3: I got what I needed!
Smoker 3: Rolling.
Smoker 3: Smoking.
Smoker 3: Done smoking.
Agent: putting paper matches
Smoker 3: Getting paper matches - Yes!
Smoker 3: I got what I needed!
Smoker 3: Rolling.
Smoker 3: Smoking.
Smoker 3: Done smoking.
Agent: putting tobacco paper
Smoker 2: Getting tobacco paper - Yes!
Smoker 2: I got what I needed!
Smoker 2: Rolling.
Smoker 2: Smoking.
Smoker 2: Done smoking.
Agent: putting paper matches
Smoker 3: Getting paper matches - Yes!
71
RESULT:
72
Thus the program for implementing cigarette smokers problem using multithreading was
executed and output was verified.
Ex.No: 7
PROBLEM
DATE: 22 3 2012.
AIM:
To write a java program to implement the multiple sleeping barbers problem.
PROBLEM STATEMENT:
To simulate multiple sleeping barbers, all in one barbershop that has a finite number of
chairs in the waiting room. Each customer is instantiated from a single customer class and each
barber is instantiated from a single barber class.
ALGORITHM:
Step 1: Import all the java files.
Step 2: Create a class called em1 to implement all the customers in the system and create
a separate class for barbers for servicing the customer.
Step 3: In the main class initialize all the variables and get the number of customers
entering in the system.
Step 4: If the number of customer is less than the no of chairs chairs then all the customer
will be served or else the customer have to wait until and unless the barber free.
PROGRAM:
import java.io.*;
import java.lang.*;
class cust
{
public int disp(int cn)
{
return(cn);
73
}
}
class em1 extends Thread
{
Barber m=new Barber();
cust c=new cust();
public synchronized void run()
{
try
{
while(m.cnum<=m.n)
{
int t=c.disp(m.cnum++);
System.out.println("Barber2 serves Customer "+t);
Thread.sleep(1500);
}
System.out.println("Barber2 sleeps ");
}
catch(Exception e){}
}
}
public class Barber
{
static int cnum=1,n,ch,n1,wt,f;
public static void main(String[] args)
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
em1 e=new em1();
74
}
}
OUTPUT:
Z:\>javac Barber.java
Z:\>java Barber
Enter no of Chairs including two barber Chairs:
5
Enter no of Customers:
6
1 Customers Left the Shop
Barber2 serves Customer 1
5 Number of customers in the shop
3 Number of customers waiting in the shop
Barber1 serves Customer 2
Barber1 serves Customer 3
Barber2 serves Customer 4
Barber1 serves Customer 5
Barber2 sleeps
Barber1 sleeps
RESULT:
Thus the program for implementing the multiple sleeping barbers problem using
multithreading was executed and output was verified.
76
NETWORK OPERATING
SYSTEMS
77
Ex.No: 8
DATE: 5 4 2012
AIM:
To write a java program to implement network operating system information retrieval.
PROBLEM STATEMENT:
Establish a lab setup for the following network operating system based pogram. It is
based on the skills in networking on you own example for identifying networking hardware,
identifying different kinds of network cabling and network interface cards can be done.
1) Identifying local area network hardware
2) Exploring local area network configuration option.
3) Verifying TCP/IP settings
4) Sharing resources
5) Testing LAN connection.
ALGORITHM:
Step 1: Import all the java files.
Step 2: Interface name is determined by using net int.getDispalyname() method.
Step 3: Cardname is determined by using netint getname().
Step 4: Local host name is find by using the inet address get.hostname() method.
Step 5: Host address is find by using the net address get.hostaddress() method.
Step 6: Hardware address is obtained by using gethardwareAddress mathid()
Step 7: Define the reachable as the boolean value if the boolean value is true, the given
address is reached and terminate the program otherwise find address repeatedly.
PROGRAM:
import java.net.*;
78
import java.util.*;
public class GetSystemIP
{
public static void main(String args[]) throws Exception
{
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
{
System.out.println("\nInterface Name : " + netint.getDisplayName());
System.out.printf("CardName: %s%n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses))
{
System.out.println("Local host Name \t : " + inetAddress.getHostName());
System.out.println("Host Address\t: " + inetAddress.getHostAddress());
InetAddress address = InetAddress.getLocalHost();
NetworkInterface ni =
NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();
System.out.println("hardware adress:");
for (int i = 0; i < mac.length; i++)
{
System.out.format("%02X%s", mac[i],(i<mac.length- 1)? "-" : "");
}
System.out.println("\n");
InetAddress address1 = InetAddress.getByName("10.0.9.8");
boolean reachable = address1.isReachable(10000);
System.out.println("Is host reachable? " + reachable);
79
}
}
}
}
OUTPUT:
Z:\OS>javac GetSystemIP.java
Z:\OS>java GetSystemIP
Interface Name : MS TCP Loopback interface
CardName: lo
Local host Name
Host Address
: localhost
: 127.0.0.1
hardware adress:
00-01-6C-5A-46-0C
Is host reachable? false
Interface Name : Marvell Yukon 88E8057 PCI-E Gigabit Ethernet Controller - Packe
t Scheduler Miniport
CardName: eth0
Local host Name
Host Address
: PG-NODE09.psr.edu.in
: 192.168.2.159
hardware adress:
00-01-6C-5A-46-0C
Is host reachable? false
RESULT:
80
Thus the java program for implementation of retrieval of network operating system
information was written and executed.
81
Ex.No.:9
ALARM CLOCK
Date: 12 4 2012
AIM:
To write a C program for implementing Alarm Clock.
PROBLEM STATEMENT:
Clock with alarm functionality shall be implemented, It shall be possible to set the time,
and to set the alarm time, the alarm shall be enabled when the alarm time is set, the alarm shall be
activated when the alarm is enabled, and when the current time is equal to the alarm time, an
activated alarm must be acknowledged. Acknowledgement of an alarm shall lead to the alarm
being disabled, the alarm is enabled again when a new alarm time is set, an alarm which is not
acknowledged shall be repeated every 10 seconds. The program shall communicate with a
graphical user interface, where the current time shall be displayed, and where the alarm time shall
be displayed when the alarm is enabled. It shall be possible to terminate the program, using a
command which is sent from the graphical user interface.
ALGORITHM:
Step 1: Import all the c files.
Step 2: Get the input from the user set the time and alarm time .
Step 3: If current time is equal to alarm time then alarm must activated and acknowledged. And
there is no acknowledgement
Step 4: The alarm is enabled again once a new alarm time is set and activates an
acknowledgement.
Step 5: Stop the program when command from GUI.
PROGRAM:
#include<stdio.h>
82
#include<conio.h>
#include<dos.h>
#include<stdlib.h>
#include<graphics.h>
#define PATH "c:\tc\bgi\"
void main()
{
int i,j,k,hour,min,g,y=1;
char msg[80];
int gd=DETECT,gm;
initgraph(&gd,&gm,PATH);
struct dostime_t t;
_dos_gettime(&t);
setcolor(14);
sprintf(msg,"The current time is: %d %02d %02d", t.hour,
t.minute,t.second);
outtextxy(150,50,msg);
outtextxy(40,100,"GIVE ONLY THE HOUR AND MINUTE YOU WANT TO
SET THE ALARM(hh,mm)");
outtextxy(97,149,"HOUR:");
gotoxy(19,10);
scanf("%d",&hour);
outtextxy(85,198,"MINUTE:");
gotoxy(20,13);
scanf("%d",&min);
outtextxy(485,400,"tanvi");
outtextxy(460,430,"jp UNIVERSITY");
if( t.hour > hour ) goto b;
else if(hour == t.hour && min<=t.minute ) goto b;
else
{
83
for(i=t.hour;i<=hour;i++)
{
for(j=t.minute;j<60;j++)
{
k=0;
while(k<60)
{
cleardevice();
k++;
setfillstyle(1,1);
bar(510,170,90,230);
settextstyle(1,0,3);
sprintf(msg,"%d %d %d",i,j,k);
outtextxy(230,188,msg);
sound(1000);
delay(100);
nosound();
sleep(1);
if(j==min && i==hour)
{
cleardevice();
while(!kbhit())
{
delay(300);
sound(1000);
setcolor(y);
outtextxy(250,200,"WAKE UP");
delay(300);
nosound();
y++;
}
84
goto a;
}}}}}
a:
getch();
exit(0);
b:
cleardevice();
outtextxy(250,250,"INVALID TIME");
getch();
}
OUTPUT:
The current time is: 11 30 43
GIVE ONLY HOUR AND MINUTE YOU WANT TO SET THE ALARM(hh,mm)
HOUR(11,35)
11
30
44
11
30
45
11
30
46
--------------------11
35
01
WAKE UP
RESULT:
85
Thus the program for implementing Real-time Operating System Using Alarm Clock was
written executed and output was verified.
DATABASE OPERATING
SYSTEMS
86
Ex. No.: 10
DATE: 19 4 2012
AIM:
To write a Java program to implement banking application for handling the concurrency
conflict that occurs between multiple client applications.
PROBLEM STATEMENT:
Assume any application (e.g. banking) on your own and do the following exercises.
1. Investigate and implement the Object Stores concurrency options.
2. Implement the concurrency conflict that occurs between multiple client applications.
3. Observe and implement the implication of nested transactions.
ALGORITHM:
CLIENT:
1. Create a menu to have a new account, check balance, withdraw, deposit and transfer.
2. Get the choice from the user and write it to the server.
3. If the choice is 1, get the account name and create the account number.
4. If the choice is 2, get the account number and display the balance.
5. If the choice is 3, get the account number and the amount of withdrawal, reduce it from
the balance and display the current balance.
6. If the choice is 4, get the account number and the amount to be deposited and update
the balance.
7. If the choice is 5, get the account number and the amount to be transferred, validate the
balance of both the accounts accordingly.
SERVER:
87
88
{
System.out.println("=================");
System.out.println("1.Create a new Account\n
2.Check Balance\n3.Withdraw\n 4.Deposit\n
5.Transfer\n 6.Exit");
System.out.println("=================");
Scanner sc=new Scanner(System.in);
int choice;
try
{
choice=sc.nextInt();
}
catch(Exception e)
{
System.out.println("Enter the Correct
Input");
continue;
}
out.writeInt(choice);
switch(choice)
{
case 1:
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the Account Name:");
String name=br.readLine();
int acno1=0;
boolean b1=false;
try
{
System.out.print("Enter the Account
Number:");
acno1=sc.nextInt();
b1=true;
}
catch(Exception e)
{
System.out.println("Enter the Account Number
Correctly");
}
out.writeBoolean(b1);
if(b1== true)
{
out.writeUTF(name);
89
out.writeInt(acno1);
}
break;
case 2:
System.out.print("Enter the Account Number:");
int acno=0;
boolean pach=false;
try
{
acno=sc.nextInt();
}
catch(Exception e)
{
System.out.println("Enter the Valid Account Number");
pach=true;
}
int bal=0;
out.writeInt(acno);
if(in.readBoolean())
{
bal=in.readInt();
System.out.println("the Balance is:"+bal);
}
else
{
if(pach==false)
{
System.out.println("Account not available");
}
}
break;
case 3:
boolean check1=false;
int acno3=0;
int amt3=0;
try
{
System.out.print("Enter the Account Number:");
acno3=sc.nextInt();
System.out.print("Enter the Ammount:");
amt3=sc.nextInt();
}
catch(Exception e)
{
System.out.println("Invalid Input");
check1=true;
90
}
if(check1==false)
{
out.writeInt(acno3);
out.writeInt(amt3);
if(in.readBoolean())
{
if(in.readBoolean())
{
System.out.println("Money is Withdrawn");
}
else
{
System.out.println("Money is not Enough to Withdraw");
}
}
else
{
System.out.println("Account is not available");
break;
}
}
break;
case 4:
System.out.print("Enter the Account Number:");
int acno4=sc.nextInt();
out.writeInt(acno4);
System.out.print("Enter the Ammount:");
int amt4=sc.nextInt();
out.writeInt(amt4);
if(in.readBoolean())
{
System.out.println("Ammount is Deposited");
}
else
{
System.out.println("Check the Account Number");
}
break;
case 5:
System.out.print("Enter the From Account:");
int tac1=sc.nextInt();
out.writeInt(tac1);
System.out.print("Enter the To Account:");
int tac2=sc.nextInt();
out.writeInt(tac2);
91
{
acno=sc.nextInt();
}
catch(Exception e)
{
System.out.println("Enter the Valid Account Number");
pach=true;
}
int bal=0;
out.writeInt(acno);
if(in.readBoolean())
{
bal=in.readInt();
System.out.println("the Balance is:"+bal);
}
else
{
if(pach==false)
{
System.out.println("Account not available");
}
}
break;
case 3:
boolean check1=false;
int acno3=0;
int amt3=0;
try
{
System.out.print("Enter the Account Number:");
acno3=sc.nextInt();
System.out.print("Enter the Ammount:");
amt3=sc.nextInt();
}
catch(Exception e)
{
System.out.println("Invalid Input");
check1=true;
}
if(check1==false)
{
out.writeInt(acno3);
out.writeInt(amt3);
if(in.readBoolean())
{
if(in.readBoolean())
94
{
System.out.println("Money is Withdrawn");
}
else
{
System.out.println("Money is not Enough to
Withdraw");
}
}
else
{
System.out.println("Account is not available");
break;
}
}
break;
case 4:
System.out.print("Enter the Account Number:");
int acno4=sc.nextInt();
out.writeInt(acno4);
System.out.print("Enter the Ammount:");
int amt4=sc.nextInt();
out.writeInt(amt4);
if(in.readBoolean())
{
System.out.println("Ammount is Deposited");
}
else
{
System.out.println("Check the Account Number");
}
break;
case 5:
System.out.print("Enter the From Account:");
int tac1=sc.nextInt();
out.writeInt(tac1);
System.out.print("Enter the To Account:");
int tac2=sc.nextInt();
out.writeInt(tac2);
System.out.print("Enter the Amount to transfer:");
int tamt=sc.nextInt();
out.writeInt(tamt);
break;
case 6:
System.exit(0);
break;
95
default:
System.out.println("Invalid Input");
break;
}
}
}
finally
{
s.close();
}
}catch(IOException e)
{
e.printStackTrace();
}}}
OUTPUT:
Server
Z:\>javac server.java
Z:\ >java server
Client
Z:\ >javac client.java
Z:\ >java client
======================
1.Create a new Account
2.Check Balance
3.Withdraw
4.Deposit
5.Transfer
6.Exit
======================
1
Enter the Account Name: Raja
Enter the Account Number: 345
======================
1. Create a new Account
96
2. Check Balance
3. Withdraw
4. Deposit
5. Transfer
6. Exit
======================
4
Enter the Account Number: 345
Enter the Ammount: 5000
Ammount is deposited
1.Create a new Account
2.Check Balance
3.Withdraw
4.Deposit
5.Transfer
6.Exit
======================
2
Enter the Account Number:345
the Balance is:5000
======================
1.Create a new Account
2.Check Balance
3.Withdraw
4.Deposit
5.Transfer
6.Exit
======================
3
Enter the Account Number:345
Enter the Ammount:1500
97
Money is Withdrawn
======================
1.Create a new Account
2.Check Balance
3.Withdraw
4.Deposit
5.Transfer
6.Exit
======================
1.Create a new Account
2.Check Balance
3.Withdraw
4.Deposit
5.Transfer
6.Exit
======================
2
Enter the Account Number:345
the Balance is:3500
======================
1.Create a new Account
2.Check Balance
3.Withdraw
4.Deposit
5.Transfer
6.Exit
======================
1
Enter the Account Name:Raja
Enter the Account Number:1001
======================
98
2
Enter the Account Number: 1001
the Balance is:2000
===================
1.Create a new Account
2.Check Balance
3.Withdraw
4.Deposit
5.Transfer
6.Exit
Sample Output:
Client:
Server:
Database Window:
100
RESULT:
Thus the Java program to implement banking application for handling the concurrency
conflict that occurs between multiple client applications. Was written and executed successfully.
101
DISTRIBUTED OPERATING
SYSTEMS
Ex.No: 11
DATE: 26 4 2012
USING RMI
AIM:
To write a java program for implementing RMI to generate n set of numbers.
PROBLEM STATEMENT:
During an RMI application, each time you run the client program thr RMI client n
the server program RMI server will generate n sets of Random number n is a positive integer.
ALGORITHM:
Step 1: Import all java files in RMI server and RMI client files.
Step 2: Create a RMI server class that will extend the remote object and implement receive
102
PROGRAM:
RMI CLIENT:
import java.io.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
public class RmiClient
{
static public void main(String args[])throws IOException
{
ReceiveMessageInterface rmiServer;
Registry registry;
String serverAddress=args[0];
String serverPort=args[1];
//String text=args[2];
int no;
no=Integer.parseInt(args[2]);
int rval[]=new int[no];
//System.out.println("Enter the numbers");
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("sending "+no+" to "+serverAddress+":"+serverPort);
try{
// get the registry
103
registry=LocateRegistry.getRegistry(
serverAddress,
(new Integer(serverPort)).intValue()
);
// look up the remote object
rmiServer=
(ReceiveMessageInterface)(registry.lookup("rmiServer"));
// call the remote method
rval=rmiServer.receiveMessage(no);
for(int i=0;i<no;i++)
System.out.println(rval[i]);
}
catch(RemoteException e){
e.printStackTrace();
}
catch(NotBoundException e){
e.printStackTrace();
}
}
}
RMI SERVER:
import java.util.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;
public class RmiServer extends java.rmi.server.UnicastRemoteObject
implements ReceiveMessageInterface
{
Int thisPort;
104
String thisAddress;
Registry registry;
registry.rebind("rmiServer", this);
}
catch(RemoteException e){
throw e;
}
}
static public void main(String args[])
{
try{
RmiServer s=new RmiServer();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
RECEIVE MESSAGE INTERFACE:
import java.rmi.*;
public interface ReceiveMessageInterface extends Remote
{
public int [] receiveMessage(int x) throws RemoteException;
}
OUTPUT:
Z:\iisem\oslab>java RmiServer
this address=node-93/192.168.2.103,port=3232
6
Z:\iisem\oslab>java RmiClient 192.168.2.103 3232 6
106
sending 6 to 192.168.2.103:3232
10
2
12
3
19
5
RESULT:
Thus the program for implementing RMI to generate n set of numbers was executed and
output was verified.
Ex.No.12
Date: 3 5 2012
AIM:
To write a java program to implement the non token based algorithm (Lamports
algorithm) for distributed mutual exclusion.
PROBLEM STATEMENT:
In the non token based approach, two or more successive rounds of messages are
exchanged among the sites to determine which site will enter the CS next. A site enters the critical
section (CS) when an assertion, defined on its local variables, becomes true. Mutual exclusion is
enforced because the assertion becomes true only at one site at any given time.
ALGORITHM:
107
PROGRAM:
import java.io.*;
import java.lang.*;
import java.util.Arrays;
public class nontoken
{
public static void executecs(int x,int[] ts,int n,int k,int[][] reqq)
{
int temp,i,j=0,j1,t=0;
temp=ts[0];
for(i=1;i<n;i++)
{
if(temp>ts[i])
{
temp=ts[i];
}
}
System.out.println("ENTERING CRITICAL SECTION.......");
System.out.println("\n");
108
System.out.println("SITE'S TIMESTAMPS");
System.out.println("\n");
for(i=0;i<n;i++)
{
j1=0;
System.out.print(i);
System.out.print("\t");
while(reqq[i][j1]!=0)
{
for(j=0;j<n;j++)
{
if(reqq[i][j1]==ts[j])
{
System.out.print("("+ reqq[i][j1] +"," +j +")");
System.out.print("\t");
}
}
j1++;
}
System.out.println("\n");
}
for(i=0;i<n;i++)
{
if((temp==ts[i]) && (ts[i]!=0))
{
System.out.println("The site " + i +" is in cs");
System.out.println("\n");
ts[i]=0;
System.out.println("RELEASING.......");
System.out.println("\n");
for(j=0;j<n;j++)
109
{
if(i!=j)
{
System.out.println(" Release message to :" +j + "
from " +i+\n );
}
}
}
}
System.out.println("Request Queue Updations ");
System.out.println("---------------------------");
System.out.println("SITES' REQUST QUEUES");
for(i=0;i<n;i++)
{
System.out.print(i);
System.out.print("\t");
sendrelease(i,reqq,n,k,ts);
}
}
public static void sendrelease(int i,int[][] reqq,int n,int k,int[] ts)
{
int j=0;
while(reqq[i][j]!=0)
{
reqq[i][j]=reqq[i][++j];
}
int t=0,j1=0;
while(reqq[i][t]!=0)
{
110
for(j1=0;j1<n;j1++)
{
if(reqq[i][t]==ts[j1])
{
System.out.print("("+ reqq[i][t]+"," +j1 +")");
System.out.print("\t");
break;
}
}
t++;
}
System.out.println("\n");
}
public static void sendrequest(int s,int r,int st,int rt,int[] ts,int reqq[][],int n)
{
int i=0,j=0,t=0;
System.out.println(" Request queue elements before getting request of :" +r);
while(reqq[r][i]!=0)
{
for(t=0;t<n;t++)
{
if(reqq[r][i]==ts[t])
{
System.out.print(" ( " + reqq[r][i] +" ," + t +")");
System.out.print("\t");
break;
}
111
}
i=i+1;;
}
reqq[r][i]=st;
Arrays.sort(reqq[r],0,(i+1));
System.out.println("\n");
System.out.println(" after getting request" );
while(reqq[r][j]!=0)
{
for(i=0;i<n;i++)
{
if(reqq[r][j]==ts[i])
{
System.out.print(" ( " + reqq[r][j] +" ," + i +")");
System.out.print("\t");
break;
}
}
j++;
}
System.out.println("\n");
}
public static void main(String args[])throws IOException
{
int i,j,n,reply,k=0,temp,k1=0;
int[] s=new int[10];
int[] ts=new int[10];
int[][] reqq=new int[10][10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of sites available");
n=Integer.parseInt(br.readLine());
112
for(i=0;i<n;i++)
{
s[i]=i;
System.out.println("Enter the timestamp value for :"+ i);
ts[i]=Integer.parseInt(br.readLine());
reqq[i][0]=ts[i];
}
System.out.println("\n");
System.out.println("SITEs' REQUEST QUEUES");
for(i=0;i<n;i++)
{
System.out.println(i+"\t"+"("+ts[i]+","+i+")");
}
System.out.println("\n");
System.out.println("REQUESTING.......");
System.out.println("\n");
for(i=0;i<n;i++)
{
System.out.println("The process " + i +" Sending the request to the sites ");
System.out.println("----------------------------------------------");
for(j=0;j<n;j++)
{
if((i!=j) && (ts[i]!=0))
{
System.out.println(" TO :" + j);
System.out.println("\n");
sendrequest(i,j,ts[i],ts[j],ts,reqq,n);
System.out.println("\n");
}
}
113
}
System.out.println("REPLY............");
System.out.println("\n");
for(i=0;i<n;i++)
{
System.out.println("SITE " + i+ " getting reply ");
System.out.println("-------------------------");
for(j=0;j<n;j++)
{
if((i!=j) && (ts[i]!=0))
{
System.out.println("Getting reply from " +j +":"+ " ( " +
ts[j] +" ,"+j+ ") \n");
}
}
}
for(j=1;j<n;j++)
{
if(ts[i]>ts[j])
{
temp=ts[j];
ts[j]=ts[i];
ts[i]=temp;
}
}
executecs(i,ts,n,k,reqq);
}
}
OUTPUT:
Z:\>javac nontoken.java
114
Z:\>java nontoken
Enter the number of sites available
2
Enter the timestamp value for: 0
3
Enter the timestamp value for: 1
2
SITEs
REQUEST QUEUES
0
1
(3,0)
(2,1)
REQUESTING
The process 0 sending the request to the sites
TO: 1
Request queue elements before getting request of :1
(2,1)
After getting request
(2,1)
(3,0)
(2,1)
(3,0)
115
(2,1) (3,0)
The site 1 is in cs
RELEASING..
Release message to :0 from 1
Request Queue Updations
SITEs REQUEST QUEUES
0
(3.0)
(3,0)
RESULT:
Thus the java program to implement the Non-Tokenbased algorithm (Lamports
algorithm) for distributed mutual exclusion was written and executed successfully.
Ex No.:13
Date: 10 5 2012
AIM:
To write a java program to implement the Token based alogorithm (Suzuki Kasamis
algorithm) for distributed mutual exclusion.
ALGORITHM:
Step 1: Getting the number of sites from the user
1.1. Generate the sequence number for the sites randomly.
1.2. Sort the sequence number of the site in ascending order.
1.3. The sites having outstanding sequence number is allowed to enter the CS first.
Step 2: REQUESTING:
116
2.1. Each site wants to enter CS send request to other site in the form of site id sequence
number
2.2. After receving the request other sites updates their request queue and sites giving the
request and the site id is placed in token queue.
Step 3: ENTERING CRITICAL SECTION:
3.1. Site with the most outstanding request value will enter the CS first.
3.2. If the site having token is being in critical section is sends the token to the outstanding
sequence number after finishing the CS.
Step 4: EXITING THE CRITICAL SECTION:
The sites id which is exiting the CS the corresponding sites id is remarked from the token
queue.
PROGRAM:
import java.util.Random;
import java.io.*;
import java.lang.*;
import java.util.Arrays;
public class Tokenbased
{
public static void sendreq(int s,int r,int snumber,int[] seqno,int[][] rn,int n,int tok[],int[] tq)
{
int i=0;
rn[s][0]=snumber;
System.out.println(" Request from " +s + " to " + r+ ":" +"("+s+","+ (snumber+1)
+") \n");
System.out.print("Token Queue "+ "\t");
for(i=0;i<(n-1);i++)
{
System.out.print( tq[i] + "\t");
}
System.out.println("\n");
117
}
break;
}
}
}
public static void main(String args[])throws IOException
{
int i,j,n,reply,k=0,temp,t1=0;
int[] tok=new int[10];
Random r=new Random();
int[][] rn=new int[10][10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of sites available");
n=Integer.parseInt(br.readLine());
int[] tq=new int[n+1];
int[] seqno=new int[n+1];
int[] nsn=new int[n+1];
int[] sn=new int[n+1];
System.out.println("\n");
for(i=0;i<n;i++)
{
tq[i]=999;
sn[i]=r.nextInt(10);
seqno[i]=sn[i];// backup the seqnumber array
System.out.println(" The Sequence number for" + i+ " is : "+sn[i]);
}
System.out.println(" \n");
Arrays.sort(sn,0,(n+1));
for(i=1;i<=n;i++)
{
System.out.print(sn[i]+ "\t");
119
}
System.out.println("\n");
for(i=n,j=0;i>0;j++,i--)
{
nsn[j]=sn[i];
//System.out.println(" The new Sequence number for " + j+ " is : "+nsn[j]);
}
temp=nsn[1];// to check for finding which site is in CS in excutecs
for(i=0;i<n;i++)
{
if(nsn[0]==seqno[i])
{
tok[i]=1;// ith site is having the token
rn[i][0]=nsn[0];
System.out.println(" Token is in " + i + " th site .so The site " + i + "
is being in Critical Section");
break;
}
}
for(i=0;i<n;i++)
{
if(tok[i]!=1)
{
System.out.println(" \n");
System.out.println("The process " + i + "Sending the request to the
sites ");
System.out.println("----------------------------------------------");
tq[t1]=i;
t1=t1+1;
for(j=0;j<n;j++)
{
120
if(i!=j)
{
System.out.println(" TO :" + j);
System.out.println("\n");
sendreq(i,j,seqno[i],seqno,rn,n,tok,tq);
System.out.println("\n");
}
}
}
}
executecs(tok,temp,tq,n,seqno);
}
}
OUTPUT:
Z:\OS>java Tokenbased
Enter the number of sites available
999
TO :2
Request from 1 to 2:(1,3)
Token Queue
99
3
121
TO :1
Request from 2 to 1:(2,7)
Token Queue
122