You are on page 1of 31

Ex.

No: 1 DATE :

MULTIPROCESSOR OPERATING SYSTEM

AIM: To write a java program for multiprocessor operating system using semaphores.

ALGORITHM:

Step 1: Start the program. Step 2: Declare the variables for more than two processes. Step 3: Declare the entry section for P1 and entry section for P2. Step 4: Define Q1:=TRUE and Q2:=TRUE. Step 5: Assign TURN:=1 and TURN:=2. Step 6: Wait while Q2 of TURN:=1 and wait while Q1 of TURN:=2. Step 7: The processes are synchronized, so that output displayed in the order ABC. Step 8: Exit from section for P1 and exit section for P2 while Q1!=FALSE and Q2:=FALSE. Step 9: Bs and Cs must be alternate in the output String i.e) after the first B is displayed, another B cannot be the displayed until a C is displayed. Step 10: Similarly, once C is displayed, another C cannot be displayed until a B is displayed. Step 11: The total number of Bs and Cs which have been displayed at any given point in the output string cannot exceed. Step 12: Utilize only semaphores, the processes are synchronized so that the output is Step 13: Execute the program. satisfied.

CODING: import java.io.Serializable; import java.util.Date; import java.util.Random; class Binarysemaphore { private boolean locked=false; Binarysemaphore(){} Binarysemaphore(boolean initial) { locked=initial; } Binarysemaphore(int initial) { locked=(initial==0); } public synchronized void p() { while(locked) { try { wait(); } catch(InterruptedException e){} } locked=true; } public synchronized void v() { if(locked) notify(); locked=false; } } class countingsemaphore { private int value=0; private int waitcount=0; private int notifycount=0; public countingsemaphore(int initial) { if(initial>0) value=initial; } public synchronized void p() { if(value<=waitcount) { waitcount++; try { do {

wait(); }while(notifycount==0); } catch(InterruptedException e) { notify(); } finally { waitcount--; } notifycount--; } value--; } public synchronized void v() { value++; if(waitcount>notifycount) { notifycount++; notify(); } } } class Pa extends ABCs implements Runnable { public void run() { while(true) { nap(1+(int)(random(500))); System.out.print(" A"); System.out.flush(); try { v(sum); } catch(Exception e){} } } } class Pb extends ABCs implements Runnable { public void run() { while(true) { nap(1+(int)(random(600))); p(C); p(sum); System.out.print(" B"); System.out.flush(); v(B); }

} } class Pc extends ABCs implements Runnable { public void run() { while(true) { nap(1+(int)(random(800))); p(B); p(sum); System.out.print(" C"); System.out.flush(); v(C); } } } class ABCs { protected static final Binarysemaphore B=new Binarysemaphore(0); protected static final Binarysemaphore C=new Binarysemaphore(1); protected static final countingsemaphore sum=new countingsemaphore(0); private static final long startTime=System.currentTimeMillis(); protected static final long age() { return System.currentTimeMillis()-startTime; } private static final Random rnd=new Random(); protected static final double random() { return rnd.nextDouble(); } protected static final double random(int ub) { return rnd.nextDouble()*ub; } protected static final void p(Binarysemaphore s) { s.p(); } protected static final void v(Binarysemaphore s) { s.v(); } protected static final void p(countingsemaphore s) { s.p(); } protected static final void v(countingsemaphore s) { s.v(); } protected static final int nap(int napTimeMs) {

long napstart=age(); try { Thread.sleep(napTimeMs); } catch(InterruptedException e) { System.out.println(e); } return(int)(age()-napstart-(long)napTimeMs); } protected static void main(String args[]) throws InterruptedException { Thread pa=new Thread(new Pa()); Thread pb=new Thread(new Pb()); Thread pc=new Thread(new Pc()); pa.start(); pb.start(); pc.start(); nap(9000); pa.stop(); pb.stop(); pc.stop(); System.exit(0); } }

OUTPUT: ABACABACABACABACABACABACABACABACABAACBAACBAACBACABACABACABAC

RESULT: Thus the Java program for multiprocessor operating system using semaphores was written, executed and verified.

EX.No: 2 DATE :

CIGRETTE SMOKERS PROBLEM

AIM: To Write a Java program for multiclass multithread that uses a monitor to synchronize the agents thread and three smokers thread.

ALGORITHM:

Step 1: Start the Program. Step 2: Declare the variables to define agent and smoker and its needs. Step 3: Use a single monitor object instantiated from a class control for synchronization. Step 4: Create the synchronized function P & V to check the value of waitcount. Step:5 No smokers, semaphores, synchronized blocks are allowed, allows only synchronized methods. Step 6: No smokers semaphores, synchronized blocks are allowed allows only synchronized methods. Step 7: No class to map inside a synchronized methods are allowed. Step 8: Each smoker thread has only thing to include inhale cigarette. Step 9: But three smokers threads are initially blocked. The agent places two randomly chosen ingredients on the table and unblocks the smoker who has remaining ingredients agents. Step 10: Execute the Program.

CODING: Agent.java import java.util.*; 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) { case 0: table.put(Table.Tobacco_Paper); break; case 1: table.put(Table.Paper_Matches); break; case 2: table.put(Table.Matches_Tobacco); break; } } } } Smoker.java import java.util.*; 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() { try { table.get(needs); System.out.println(getName()+": Rolling."); sleep(Math.abs(rand.nextInt())%1000); System.out.println(getName()+": Smoking."); sleep(Math.abs(rand.nextInt())%1000); System.out.println(getName()+": Done smoking.");

table.Donesmoking(); }catch(InterruptedException e){} } } Table.java import java.util.*; 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) { if((contains&what)!=what) { try { System.out.println(Thread.currentThread().getName()+":getting"+contains(what)+"-No!"); wait(); }catch(InterruptedException e){} } System.out.println(Thread.currentThread().getName()+":getting"+contains(what)+"-Yes!"); contains=contains^what; } 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; } } Tablecs.java import java.util.*; public class Tablecs extends Table { Tablecs Table; } Cigar.java import java.util.*; public class Cigar { public static void main(String args[]) { smoker s1,s2,s3; agent a; Table t=new Table(); a=new agent(t,"agent"); s1=new smoker(t,"smoker1",Table.Paper); s2=new smoker(t,"smoker2",Table.Matches); s3=new smoker(t,"smoker3",Table.Tobacco); a.start(); s1.start(); s2.start(); s3.start(); } }

OUTPUT: smoker1:gettingtobaccomatches-No! smoker2:gettingtobaccopaper-No! agent:puttingtobaccopaper smoker3:gettingpapermatches-No! smoker1:gettingtobaccomatches-Yes! smoker2:gettingtobaccopaper-Yes! smoker1: Rolling. smoker2: Rolling. smoker1: Smoking. smoker2: Smoking. smoker2: Done smoking. smoker1: Done smoking. agent:puttingtobaccopaper smoker3:gettingpapermatches-Yes! smoker3: Rolling. agent:puttingpapermatches smoker3: Smoking. smoker3: Done smoking. agent:puttingpapermatches

RESULT: Thus the Java program for multiclass multithread that uses a monitor to synchronize the agents thread and three smokers thread was written, executed and verified.

10

EX.No : 3 DATE :

SLEEPING BARBERS PROBLEM

AIM: To write a multiclass multithread java program that simulates multiple sleeping barbers.

ALGORITHM: Step1: Start the program. Step 2: Perform P(lock) and randNum=rand(1,3). Step 3: If the number of free seats is greater than 0, are any customers sitting down on a chair, notify the barber who is waiting that there is a customer. Step 4: V(access seats) dont need to lock the chairs anyone, now its this customers turn, but wait if wait the barber if busy, here the customer is having his hair cut. Step 5: Else there are no free seats Lock(V)(access seats) but release the lock or the seats, customers leaves without a haircut. Step 6: Stop the program.

11

CODING: class Semaphore extends Object { private int count; public Semaphore(int startingCount) { count=startingCount; } public void down() { synchronized(this) { while(count<=0) { try { wait(); } catch(InterruptedException ex) {} } count--; } } public void up() { synchronized(this) { count++; if(count==1) { notify(); } } } } public class SleepingBarber extends Thread { public static Semaphore customers=new Semaphore(0); public static Semaphore barbers=new Semaphore(0); public static Semaphore mutex=new Semaphore(1); public static int waiting=0; public static final int CHAIRS=5; class Barber extends Thread { private int myNumber; public Barber(int i) { myNumber=i; } public void run() { while(true) {

12

customers.down(); mutex.down(); waiting=waiting-1; barbers.up(); mutex.up(); cut_hair(); } } public void cut_hair() { System.out.println("Barber"+myNumber+"is cutting hair"); try { sleep(7500); } catch(InterruptedException ex) {} } } private class Customer extends Thread { private int myNumber; public Customer(int i) { myNumber=i; } public void run() { mutex.down(); if(waiting<CHAIRS) { waiting=waiting+1; customers.up(); mutex.up(); barbers.down(); get_haircut(); } else { mutex.up(); } } public void get_haircut() { System.out.println("Customers"+myNumber+"is getting his haircut"); try { sleep(10000); } catch(InterruptedException ex) {} } }

13

public static void main(String args[]) { SleepingBarber holder=new SleepingBarber(); holder.start(); } public void run() { final int BARBERS=3; Barber aBarber; Customer aCustomer; for(int i=0;i<BARBERS;i++) { aBarber=new Barber(i); aBarber.start(); } int customerNumber=0; while(true) { aCustomer=new Customer(customerNumber++); aCustomer.start(); try { sleep(1000); } catch(InterruptedException ex){}; } } }

14

OUTPUT: Barber0is cutting hair Customers0is getting his haircut Barber1is cutting hair Customers1is getting his haircut Barber2is cutting hair Customers2is getting his haircut Customers3is getting his haircut Barber0is cutting hair Barber1is cutting hair Customers4is getting his haircut Barber2is cutting hair Customers5is getting his haircut Barber0is cutting hair Customers6is getting his haircut Customers7is getting his haircut Barber1is cutting hair Barber2is cutting hair Customers8is getting his haircut Customers9is getting his haircut Barber0is cutting hair

RESULT: Thus the Java program for multiclass multithread java program that simulates multiple sleeping barbers was written, executed and verified.

15

EX.NO: 4 DATE:

NETWORK OPERATING SYSTEM

Aim: To write a program for activating LAN connections between two systems.

Algorithm:

Step 1: Start the program. Step 2: Declare the IP address and MAC address to open a connection between corresponding systems. Step 3: Type ipconfig/all in command prompt, we get the IP address and MAC address of own system. Step 4: Type the MAC address as different formats. Step 5: Type the source code. Step 6: Compile the program and execute. Step 7: Run the program by declaring IP address and MAC address of destination.

16

CODING: import java.io.*; import java.net.*; public class Wakeonlan { public static final int PORT=9; public static void main(String[ ] args) { if(args.length!=2) { System.out.println("usuage:javaWakeOnLan1<broadcast-ip><mac-address>"); System.out.println ("Example:java WakeOnLan1 172.15.169.7 00-15-58-AC-0C-20"); System.out.println ("Example:java WakeOnLan1 172.15.169.8 00-15-58-AC-0C-27"); System.exit(1); } String ipStr=args[0]; String macstr=args[1]; try { byte[ ] macBytes=getMacBytes(macstr); byte[] bytes=new byte[6+16*macBytes.length]; for(int i=0;i<6;i++) bytes[i]=(byte)0xff; for(int i=6;i<bytes.length;i+=macBytes.length) System.arraycopy(macBytes, 0,bytes,i,macBytes.length); InetAddress address = InetAddress.getByName(ipStr); DatagramPacket packet = new DatagramPacket(bytes,bytes.length,address,PORT); DatagramSocket socket= new DatagramSocket(); socket.send(packet); socket.close(); System.out.println("wake on lan packet sent"); } catch(Exception e) { System.out.println("failed to send wake on lan packet:+e"); System.exit(1); } } private static byte[] getMacBytes(String macstr) throws IllegalArgumentException { byte[] bytes=new byte[6]; String[] hex=macstr.split("(\\:|\\-)"); if(hex.length!=6) { throw new IllegalArgumentException("Invalid MAC address"); } try { for(int i=0;i<6;i++) bytes[i]=(byte)Integer.parseInt(hex[i],16); } catch(NumberFormatException e) { throw new IllegalArgumentException("invalid hex digit in MAC address"); }

17

return bytes; } }

OUTPUT: C:\jdk1.3\bin>javac WakeOnLan.java C:\jdk1.3\bin>java WakeOnLan 172.15.169.7 00-15-58-AC-0C-20 Wake on LAN packet sent

RESULT: Thus the Java program for activating LAN connections between two systems was written, executed and verified.

18

EX.NO:5 DATE :

REAL TIME OPERATINGSYSTEM

AIM: To write a program using Real time operating system for implementing an alarm clock.

ALGORITHM: Step 1: Start the program. Step 2: Display init is used for initialization and shall be called from the main function of the program before the processes are created. Step 3: Display alarm time a shows the current time and shall be called when a new alarm time is set. Step 4: Display time is used to display the current time and shall be called by the clock process. Step 5: Erase the alarm time, erases the displayed alarm time and shall be called when the user acknowledges an alarm. Step 6: Display alarm text is used to show an alarm activation and the user is informed that the alarm has been activated. Step 7: when the alarm is activated the first time and when the alarm is activated repeatedly. Step 8: Erase alarm text,erase the information displayed by displays the alarm text. Step 9: Stop the program.

19

CODING: #include<stdio.h> #include<conio.h> #include<dos.h> struct clk { int hh,mm,ss; }c1,c2; void clock(int *h1,int *m1,int *s1) { *s1=*s1+1; if(*s1==60) { *s1=0; *m1=*m1+1; if(*m1==60) { *m1=0;*h1=*h1+1; if(*h1==24) *h1=0; } } } void timer(int *h,int *m,int *s) { if((*s)!=0) { *s=*s-1; } else if((*s)==0) { if(*m!=0) { *s=59;*m=*m-1; } else if(*m==0) { if(*h!=0) { *m=59;*h=*h-1; } } } } void alarm() { int i; while(!kbhit()) { for(i=0;i<2;i++) { sound(5000); delay(100);

20

nosound(); delay(200); } delay(500); } } void main() { char ch; struct time t; clrscr(); printf("\nPress:-\n\tA: for alarm Clock\n\tT: for Timer\n"); printf("\Enter your Choice:"); ch=getche(); switch (ch) { case 'A': case 'a': { printf("\n\n\n24 hr Format(HH:MM:SS)"); gettime(&t); c1.hh=t.ti_hour; c1.mm=t.ti_min; c1.ss=t.ti_sec; printf("\nEnter alarm time : "); scanf("%d:%d:%d",&c2.hh,&c2.mm,&c2.ss); if(c2.hh>24||c2.mm>60||c2.ss>60) { printf("\n\n\tERROR: Invalid time.\n\tRestart the program."); delay(2500);exit(0); } while((c1.ss!=c2.ss)||(c1.hh!=c2.hh)||(c1.mm!=c2.mm)) { clrscr(); printf("\n\nAlarm time: %02d:%02d:%02d\n",c2.hh,c2.mm,c2.ss); printf("\nCurrent Time: %02d:%02d:%02d",c1.hh,c1.mm,c1.ss); clock(&c1.hh,&c1.mm,&c1.ss); delay(1000); }; clrscr(); printf("\n\n\n\n\t\t\t\tAlarm time reached\n\n\t\t\t\tPress any to Exit."); alarm(); exit(0); } break; case 'T': case 't': { printf("\n\n\nEnter time for timer (HH:MM:SS): "); scanf("%d:%d:%d",&c1.hh,&c1.mm,&c1.ss); while(c1.hh>0||c1.mm>0||c1.ss>0) {

21

clrscr(); printf("The Current Time:\n"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t"); printf("%02d:%02d:%02d",c1.hh,c1.mm,c1.ss); timer(&c1.hh,&c1.mm,&c1.ss); delay(1000); } clrscr(); printf("00:00:00"); alarm(); exit(0); } break;

default: { printf("\n\tInvalid Input\n\n\tPlease restart the program"); delay(2500);exit(0); } } }

22

OUTPUT: Press:A: for alarm Clock T: for Timer Enter your Choice:A 24 hr Format(HH:MM:SS) Enter alarm time : 22:30:50 Alarm time: 22:20:50 Current Time: 22:19:53 Alarm time reached Press any to Exit. Press:A: for alarm Clock T: for Timer Enter your Choice: T Enter time for timer (HH:MM:SS): 22:25:20 The Current Time: 22:25:06

RESULT: Thus the Java program using real time operating system for implementing an alarm clock was written, executed and verified.

23

EX.No: 6 DATE :

TRANSACTIONS AND CONCURRENCY DATABASE OPERATING SYSTEMS

AIM: To create a banking application to implement objects concurrency options and to implement nested transactions.

ALGORITHM: Step 1: Start the program. Step 2: Import the packages. Step 3: we create two java classes: one acts as a server and the other acts as a client. Step 4: In the client java program, socket is created with the IP Address of the system and the port number. Step 5: The user is provided with appropriate options provided to create a new account check balance withdraw deposit. Step 6: In the server and appropriately, the options are provided from the client end to the server end. Step 7: For each transactions, the database connectivity and the socket is opened and closed appropriately. Step 8: Save the program. Step 9: Compile the server and client program separately. Step 10: Stop the process.

24

CODING: import java.sql.*; import java.io.*; class SelectProducts { public static void main(String args[]) throws IOException { try { String AcN; DataInputStream in=new DataInputStream(System.in); System.out.println(" Enter the Account Number "); AcN=in.readLine(); Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" ); Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", " db2admin " ); Statement statement = con.createStatement( ); ResultSet rs = statement.executeQuery("SELECT AcNo,NAME,Balance FROM CustomerInfo"); while ( rs.next( ) ) { String name = rs.getString( "NAME" ); float balance=rs.getString( "Balance" ); String acnn=rs.getString( "AcNo" ); if(acnn==AcN) { System.out.println("Name: "+name); System.out.println("Balance: "+balance); } } statement.close( ); con.close( ); } catch( Exception e ) { e.printStackTrace( ); } }

25

OUTPUT:

Enter the Account Number 1131130401001 Name : Ranjithkumar

Balance : 23324.50

RESULT: Thus the Java program for creating a banking application to implement objects concurrency options and to implement nested transactions was written, executed and verified.

26

Ex.No:7 Date:

DISTRIBUTED OPERATING SYSTEM

AIM: To write a java program to design a RMI lottery application using distributed operating systems.

ALGORITHM:

LOTTERY CLIENT: Step 1: set client machine address and server port address. Step 2: Using socket() create socket for server. Step 3: Read the message given in the client. Step 4: Send the message to the server from client. Step 5: Receive the same message from the server. Step 6: Print the message.

LOTTERY SERVER: Step 1: Set server port address using socket(). Step 2: Create a server by specifying server port. Step 3: Receive the message from client and resend the message to client. Step 4: Stop the process.

27

CODING: Remote Method Declaration: (ReceiveMsg.java) import java.rmi.*; public interface ReceiveMsg extends Remote { int[] receiveMessage(int x) throws RemoteException; } Server Implementation: (RmiServer.java) import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; import java.net.*; import java.util.Random; public class RmiServer extends UnicastRemoteObject implements ReceiveMsg { int thisPort; String thisAddress; Random r= new Random(); Registry registry; // rmi registry for lookup the remote objects. public int[] receiveMessage(int x) throws RemoteException { int val[]=new int[x]; int n; for(int i=0;i<x;i++) { n=r.nextInt(10000); val[i]=n; System.out.println("Lottory Selected:"+n); } return val; } public RmiServer() throws RemoteException { try { thisAddress= (InetAddress.getLocalHost()).toString(); }

28

catch(Exception e) { throw new RemoteException("can't get inet address."); } thisPort=3232; // this port(registrys port) System.out.println("this address="+thisAddress+" ,port="+thisPort); try { registry = LocateRegistry.createRegistry(thisPort); registry.rebind("rmiServer",this); } catch(RemoteException e) { throw e; } } public static void main(String args[]) { try { RmiServer s=new RmiServer(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } Client Implementation: (RmiClient.java) import java.rmi.*; import java.rmi.registry.*; import java.io.*; import java.net.*; public class RmiClient { public static void main(String args[]) throws IOException

29

{ReceiveMsg msg;

Registry registry; String serverAddress; String serverPort; String text; try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the Host Name:"); serverAddress=br.readLine(); System.out.println("Enter the Port Address:"); serverPort=br.readLine(); System.out.println("Enter total number of lotory lots:"); int n=Integer.parseInt(br.readLine()); registry=LocateRegistry.getRegistry(serverAddress,(new Integer(serverPort)).intValue()); String li[]=registry.list(); System.out.println("The avilable remote objects in registry are:"); for(int i=0;i<li.length;i++) System.out.println(li[i]); msg=(ReceiveMsg)(registry.lookup("rmiServer")); int x[]=new int[n]; x=msg.receiveMessage(n); for(int i=0;i<n;i++) { System.out.println(x[i]); } } catch(RemoteException e) { e.printStackTrace(); } catch(NotBoundException e) { e.printStackTrace(); } }}

30

OUTPUT:

C:\jdk1.3\bin> javac ReceiveMsg.java C:\jdk1.3\bin> java RmiServer.java C:\jdk1.3\bin> java RmiClient.java C:\jdk1.3\bin> Rmic RmiServer

C:\jdk1.3\bin> java RmiServer

This address=ranjithkani-pc/192.168.0.102 ,port=3232 Lottory Selected :3097 Lottory Selected :197

C:\jdk1.3\bin> java RmiClient Enter the Host Name: 192.168.0.102 Enter the port Address: 3232 Enter total number of lottery lots 2 The available lottery numbers in registry are Rmiserver 3097 197

RESULT:

Thus the Java program to design a RMI lottery application using distributed operating systems was written, executed and verified.

31

You might also like