You are on page 1of 88

Ex.

No:01
Date:18/02/10

SEMAPHORES - MULTIPROCESSOR OPERATING SYSTEMS


Aim:
To write a java program for implementing semaphores in multiprocessor OS.

Algorithm:
* 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 have 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.

* Examples
* AACB

-- invalid, violates a)

* ABACAC

-- invalid, violates b)

* AABCABC
* AABCAAABC
* AAAABCBC

-- invalid, violates c)
-- valid
-- valid

* AB

-- valid

*/
An Algorithm For More Than Two Processes:/* Entry section for P1 */ /* Entry section for P2 */
Q1 := True; Q2 := True;
TURN := 1; TURN := 2;
wait while Q2 and TURN := 1; wait while Q1 and TURN := 2;
/* Exit section for P1 */ /* Exit section for P2 */
Q1 := False; Q2 := False;

Both in this algorithm and in all of the previous ones, the processes busy-wait
until they are allowed to enter the critical section. One might wonder why these
algorithms busy-wait instead of simply context-switching to another ready process. At
the beginning of this paper, we made the assumption that critical sections were usually
very small; this would imply that any process busy-waiting on a lock would likely
wait for a fairly short period of time. The overhead of context-switching is usually
large enough that busy-waiting is more efficient. For critical sections that are longer,
such as those with disk access, the above algorithms can be used as low-level building
blocks for higher-level semaphores.

PROGRAM: ABCs.java
import java.io.Serializable;
import java.util.Date;
import java.util.Random;
class BinarySemaphore {
private boolean locked = false;
BinarySemaphore() {} // constructors
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;
}}
3

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) {
4

notifyCount++;
notify();
}
}}
class Pa extends ABCs implements Runnable { // extend ABCs to
// access semaphore sum
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(800)));
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);
5

System.out.print("C"); System.out.flush();
V(C);
}
}}
class ABCs {
protected static final BinarySemaphore B
= new BinarySemaphore(0);

// these semaphores

// are static

protected static final BinarySemaphore C


= new BinarySemaphore(1);

// so subclasses

// Pa, Pb,

protected static final CountingSemaphore sum // and Pc share


= new CountingSemaphore(0);

// them

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(); }
6

protected static final int nap(int napTimeMS) {


long napStart = age();
try {
Thread.sleep(napTimeMS);
} catch (InterruptedException e) {
System.err.println("interrupted out of sleep");
}
return (int) (age() - napStart - (long) napTimeMS);
}
public 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);
}}

OUT PUT:-

Result:
Thus the given program was coded and executed successfully.

Ex.No:02
Date:25/02/10

MULTITHREADING - MULTIPROCESSOR OPERATING SYSTEMS


Aim:
To write a java program for solving the cigarette problem using multithreading.

Problem Description:Consider a system with three smoker processes and one agent process. Each
smoker continuously rolls a cigarette and then smokes it. But to roll and smoke a
cigarette, the smoker needs three ingredients: tobacco, paper, and matches. One of the
smoker processes has paper, another has tobacco, and the third has matches. The agent
has an infinite supply of all three materials. The agent places two of the ingredients on
the table. The smoker who has the remaining ingredient then makes and smokes a
cigarette, signaling the agent on completion. The agent then puts out another two of
the three ingredients, and the cycle repeats.

ALGORITHM:The code for the agent process.


1 do forever {
2 P( lock );
3 randNum = rand( 1, 3 ); // Pick a random number from 1-3
4 if ( randNum == 1 ) {
5 // Put tobacco on table
6 // Put paper on table
7 V( smoker_match ); // Wake up smoker with match
8 } else if ( randNum == 2 ) {
9

// Put tobacco on table

10 // Put match on table


11 V( smoker_paper ); // Wake up smoker with paper
12 } else {
13 // Put match on table
14 // Put paper on table
10

15 V( smoker_tobacco ); } // Wake up smoker with tobacco


16 V( lock );
17 P( agent ); // Agent sleeps
18 } // end forever loop
The code to one of the smokers. The others are analogous.
1 do forever {
2 P( smoker_tobacco ); // Sleep right away
3 P( lock );
4 // Pick up match
5 // Pick up paper
6 V( agent );
7 V( lock );
8 // Smoke (but don't inhale).
9 }
PROGRAM :-

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();
}
11

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();
12

needs=Table.Everything^what;
}
public void run()
{

while(true)

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;
13

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){}

14

}
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;
}
Cigarette.java
import java.util.*;
15

public class cigarette


{
public static void main(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();
}
}

OUTPUT:
Smoker 2:Smoking.
Smoker 2:Done Smoking.
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-No!
Agent:puttingtobaccomatches
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-No!
Smoker 1:gettingtobaccomatches-Yes!
Smoker 1:Rolling.
16

Smoker 1:Smoking.
Smoker 1:Done Smoking.
Smoker 1:gettingtobaccomatches-No!
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Agent:puttingtobaccopaper
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-Yes!
Smoker 2:Rolling.
Smoker 1:gettingtobaccomatches-No!
Smoker 2:Smoking.
Smoker 2:Done Smoking.
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-No!
Agent:puttingtobaccopaper
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-Yes!
Smoker 1:gettingtobaccomatches-No!
Smoker 2:Rolling.
Smoker 2:Smoking.
Smoker 2:Done Smoking.
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-No!
Agent:puttingtobaccomatches
Smoker 2:gettingtobaccopaper-No!
Smoker 3:gettingpapermatches-No!
Smoker 1:gettingtobaccomatches-Yes!
Smoker 1:Rolling.
Smoker 1:Smoking.
Smoker 1:Done Smoking.
Smoker 3:gettingpapermatches-No!
Smoker 2:gettingtobaccopaper-No!
Smoker 1:gettingtobaccomatches-No!

17

Result:
Thus the given program was coded and executed successfully.

Ex.No:03
Date:04/03/10

MULTIPLE SLEEPING BARBERS - MULTIPROCESSOR OPERATING


SYSTEMS

Aim:
18

Write a multi-class multithreaded Java program that simulates 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, each barber is
instantiated from a single Barber class.

PROBLEM DESCRIBTION:-

The Sleeping-Barber Problem. A barbershop consists of a waiting room with n


chairs and the barber room containing the barber chair. If there are no customers to be
served, the barber goes to sleep. If a customer enters the barbershop and all chairs are
occupied, then the customer leaves the shop. If the barber is busy but chairs are
available,then the customer sits in one of the free chairs. If the barber is asleep, the
customer wakes up the barber.

ALGORITHM:

The Barber (Thread/Process):

while(true) { //runs in an infinite loop


P(Customers) //tries to acquire a customer - if none is available he goes to sleep
P(accessSeats) //at this time he has been awakened - want to modify the number of
available seats
NumberOfFreeSeats++ //one chair gets free
V(Barber) //the barber is ready to cut
V(accessSeats) //we don't need the lock on the chairs anymore
//here the barber is cutting hair
}

The Customer (Thread/Process):

while(true) { //runs in an infinite loop


P(accessSeats) //tries to get access to the chairs
if ( NumberOfFreeSeats > 0 ) { //if there are any free seats
NumberOfFreeSeats-- //sitting down on a chair
V(Customers) //notify the barber, who's waiting that there is a customer
V(accessSeats) //don't need to lock the chairs anymore
P(Barber) //now it's this customers turn, but wait if the barber is busy
//here the customer is having his hair cut
19

} else { //there are no free seats


//tough luck
V(accessSeats) //but don't forget to release the lock on the seats
//customer leaves without a haircut
}
}

PROGRAM :
Semaphore.java:
20

class Semaphore extends Object


{
private int count;
public Semaphore(int startingCount){
count = startingCount;
}
public void down(){
Synchronized (this) {
while (count <= 0) {
try {
wait();
} catch (Interrupted Exception ex) {
}}
count--;
}}
public void up(){
synchronized (this) {
count++;
if (count == 1 ) {
notify();
}}
}}

SleepingBarber.java
class Semaphore extends Object
21

{
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;
22

public static final int CHAIRS = 5;


class Barber extends Thread {
private int myNumber; // Id for the Barber
public Barber(int i) { // Constructor for the Barber
myNumber = i;
}
public void run(){ // What a barber does
while(true) {
customers.down(); // Go to sleep if no customers
mutex.down(); // Acquire access to waiting
waiting = waiting - 1; // Decrement count of waiting
barbers.up(); // One barber is now ready to cut
mutex.up(); // Release waiting
cut_hair(); // Noncritical region
}}
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;
}
23

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("Customer " + myNumber
+ " is getting his hair cut");
try {
sleep(10000);
} catch (InterruptedException ex){ }
}}
public static void main(String args[]) {
SleepingBarber holder = new SleepingBarber();
holder.start();
}
public void run(){
final int BARBERS = 3;
Barber aBarber;
Customer aCustomer;
24

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) {};
}} }

SleepingBarberD.java
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) {
25

}}
count--;
}}
public void up(){
synchronized (this) {
count++;
if (count == 1 ) {
notify();
}}
}}
public class SleepingBarberD 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) {
customers.down();
mutex.down();
waiting = waiting - 1;
26

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();
try { //random sleep
sleep(10000);
} catch (InterruptedException e) {}
try {
sleep(10000);
27

} catch (InterruptedException e) {}
try {
sleep(10000);
} catch (InterruptedException e) {}
barbers.down();
get_haircut();
} else {
mutex.up();
}}
public void get_haircut(){
System.out.println("Customer " + myNumber
+ " is getting his hair cut");
try {
sleep(10000);
} catch (InterruptedException ex){ }
}}
public static void main(String args[]) {
SleepingBarberD holder = new SleepingBarberD();
holder.start();
}
public void run(){
final int BARBERS = 3;
Barber aBarber;
Customer aCustomer;
for(int i=0; i<3;i++)
{
28

aBarber = new Barber(i);


aBarber.start();
}
int customerNumber = 0;
while(true){
aCustomer = new Customer(customerNumber++);
aCustomer.start();
try {
sleep(1000);
} catch(InterruptedException ex) {};
}} }

29

OUTPUT:Customer 32 is getting his hair cut


Barber 0 is cutting hair
Customer 38 is getting his hair cut
Barber 1 is cutting hair
Customer 39 is getting his hair cut
Barber 2 is cutting hair
Customer 40 is getting his hair cut
Customer 45 is getting his hair cut
Barber 0 is cutting hair
Barber 1 is cutting hair
Barber 2 is cutting hair
Customer 47 is getting his hair cut
Customer 48 is getting his hair cut
Barber 0 is cutting hair
Customer 53 is getting his hair cut
Barber 1 is cutting hair
Customer 54 is getting his hair cut
Barber 2 is cutting hair
Customer 55 is getting his hair cut
30

Customer 60 is getting his hair cut


Barber 0 is cutting hair
Barber 1 is cutting hair
Barber 2 is cutting hair
Customer 62 is getting his hair cut
Customer 63 is getting his hair cut
Barber 0 is cutting hair
Customer 68 is getting his hair cut
Barber 1 is cutting hair
Customer 69 is getting his hair cut
Barber 2 is cutting hair
Customer 70 is getting his hair cut
Barber 0 is cutting hair
Customer 75 is getting his hair cut
Barber 1 is cutting hair
Barber 2 is cutting hair
Customer 77 is getting his hair cut
Customer 78 is getting his hair cut
Barber 0 is cutting hair
Customer 83 is getting his hair cut
Barber 1 is cutting hair
Customer 84 is getting his hair cut
Barber 2 is cutting hair

31

Result:
Thus the given program was coded and executed successfully.

Ex.No:04
Date:19/03/10

Network operating systems


Aim:
To Establish a Lab setup for the following network operating systems based
programs based on the skills in networking on your own. E.g. for identifying
networking hardware, identifying different kinds of network cabling and network
interface cards can be done.
IDENTIFYING LOCAL AREA NETWORK HARDWARE
When you have several computers, it can be convenient to connect them to
each other to create a local area network (LAN). Setting up such a network costs very
little, contrary to what people may think. Here are a few advantages you could enjoy
by setting up a local area network:

File transfers;

Sharing of resources (internet connection sharing, printer sharing, shared disks,


etc.);

Mobility (in the case of a wireless network);

Discussion (mainly when the computers are remote);


32

Network games.

Network architecture
To create an RJ45 local area network, it is recommended that you adopt a so-called
"star" structure, where the computers are each connected to the hub via an RJ45 cable.
A hub is a device that transfers data from one computer to another. The choice of hub
will be made in function of the number of connected computers in order to have
enough plugs (called "ports") on the hub.
In the event of a large network or a network with substantial bandwidth requirements,
a switch will favourably replace the hub, as it makes it possible to distribute packets
only to the computers concerned, whereas a hub systematically sends packets to all
connected computers.
The structure of such a network looks like this:

If you want to connect two computers only, it is possible to avoid using a hub, by
directly connecting the two computers with a crossover RJ45 cable.

33

WakeOnLan.java
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("Usage: java WakeOnLan <broadcast-ip> <mac-address>");
System.out.println("Example: java WakeOnLan 172.15.169.7 00-15-58-A3-4F-20");
System.out.println("Example: java WakeOnLan 172.15.169.8 00-15-58-A3-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);
34

DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);

35

DatagramSocket socket = new DatagramSocket();


socket.send(packet);
socket.close();
System.out.println("Wake-on-LAN packet sent.");
}
catch (Exception e) {

36

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.");
}
return bytes;
}}

37

TO FIND MAC ADDRESS AND IP ADDRESS


Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
Z:\>ipconfig/all
Windows IP Configuration
Host Name . . . . . . . . . . . . : me-7
Primary Dns Suffix . . . . . . . : cse.edu
Node Type . . . . . . . . . . . . : Unknown
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
DNS Suffix Search List. . . . . . : cse.edu
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Realtek RTL8139 Family PCI Fast Ethernet NIC
Physical Address. . . . . . . . . : 00-15-58-A3-4F-20
Dhcp Enabled. . . . . . . . . . . : No
IP Address. . . . . . . . . . . . : 172.15.169.7
Subnet Mask . . . . . . . . . . . : 255.255.192.0
Default Gateway . . . . . . . . . : 172.15.150.100
DNS Servers . . . . . . . . . . . : 172.15.128.253
172.15.150.100

38

OUTPUT
D:\Java\jdk1.5.0_06\bin>javac WakeOnLan.java
D:\Java\jdk1.5.0_06\bin>java WakeOnLan 172.15.169.8 00-15-58-A3-0C-27
Wake-on-LAN packet sent.

Result:
Thus the given program was coded and executed successfully.

39

40

Ex.No:05
Date:26/03/10

Real time operating systems

Aim:
To write a real-time program implementing an alarm clock .

PROBLEM DESCRIPTION:A clock with alarm functionality shall be implemented. It shall be possible to
set the time. It shall be possible 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:

Display init is used for initialization, and shall be called from the main
function of the program, before the processes are created.
Display time displays the current time, and shall be called by the clock
process.
Display alarm time shows the current alarm time, and shall be called when a
new alarm time is set.
Erase alarm time erases the displayed alarm time, and shall be called when the
user acknowledges an alarm.
Display alarm text is used to show an alarm activation, and shall be called
when the user shall be informed that the alarm has been activated,i.e. when the
alarm is activated the first time, and when the alarm is activated repeatedly
(which is every 10 seconds, according to the above stated requirments).
Erase alarm text erases the information displayed by display alarm text, and
shall be called when the user acknowledges an alarm.
41

PROGRAM:#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)
42

{
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);
43

delay(100);
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)
{
44

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)
{
clrscr();
printf("The Current Time:\n");
45

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("Program Written by: Anshu Krishna\n");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t");
printf("00:00:00");
alarm();
exit(0);
}
break;
default:
{
printf("\n\tInvalid Input\n\n\tPlease restart the program");
delay(2500);exit(0);
}
}}

46

OUTPUT:

47

48

49

Result:
Thus the given program was coded and executed successfully.

Ex.No:06
Date:05/04/10

Database operating systems


Assume any application(e.g.banking) on your own and do the following exercises.

50

1. Investigate and implement the ObjectStore's concurrency options.


The executions of transactions are all or none. The interleaving of multiple
transactions is serializable. Update is atomic.

Transaction
Object
ClientsTransaction
SchedulerObject Objects
managerObjects
Scheduler
Clients manager
manager
manager

ALGORITHM:-

(i)
(ii)
(iii)
(iv)

Creation of bindings to the bank account object;


Start of the application transaction;
Method invocations; as a part of a given invocation the object will be
locked in read or write mode; and
Commit/abort of the transaction.

2. Implement the concurrency conflict that occurs between multiple client


applications.

Reducing the preconditionsthat is, reducing the dependencies of the request


reduces the chance of optimistic failure.

Reducing the chance of the preconditions being invalid reduces the chance of
optimistic failure.

Use postings and business actions to achieve the first.

Try to change arbitrary data into either predictable reference data or into
personal data to achieve the second.

For predictable reference data we do not have to design for issues caused by
concurrent change; we can just assume it will never happen, and that it is not worth
the effort to design elaborate exception handling.
For arbitrary data we have to design for exceptions caused by concurrent change.
When we use arbitrary data, we accept the chance that we will have to tell the user
51

that we encountered a concurrency issue. We accept that we will have to tell the user
that the transaction was rejected, or that we have to ask the user for a resolution. We
may have to design how to turn arbitrary data into predictable reference data, and also
design for multiple validity periods of specific information, such as an address change.
Arbitrary data may be problematic, and we should try to avoid using it as a
precondition. That is, we should try to avoid using arbitrary data to formulate requests
to the service, and avoid using it to support the users' decisions.
For personal data we can accept exceptions, because they're easy to explain to the
user, and should be expected. (The user caused them in the first place, for instance, by
making offline changes on two systems.)
Almost all recommendations in this article concern the design of the service
interaction, and can thus be formulated as recommendations for good service design.

Confine pessimistic resource usage


I recommend using pessimistic concurrency behavior only in the confines of a
system that is completely under control. That is, a system in which you control
how long a user or process can lock or reserve resources. This reduces and
controls the impact of resource use on other users.

Limit optimistic updates


I recommend limiting optimistic concurrency behavior to updates of master
data with very limited side effects, and only for master data that does not
change too oftenin other words, only for changes with a small or acceptable
likelihood of running into an optimistic failure.

Design business actions


I recommend using business actions for formulating requests. By formulating
the request and the prerequisites or assumptions, one can reduce the chance of
conflict and make that chance explicit.

Design postings

52

I recommend using the pattern of postings as the preferred type of business


action for communicating with services, to minimize the occurrence of
optimistic failures.

Use the journal pattern


I recommend using what I call the journal pattern on top of postings and
business actions. It is easy to explain to business managers, and it makes the
design more reliable. It helps in making the requests uniquely identifiable, thus
supporting an audit trail, and it helps in making the dependencies between
business actions manageable.
I recommend not changing the postings or business actions in the journal, but
rather adding new "compensating" postings or business actions.
The journal is part of the "data contract" of the service; the service publishes
the schema of the journal. The journal can manage the dependencies between
the posting requests it contains, it can document the audit trail, and its unique
identification can prevent double postings.

Reduce the dependency on arbitrary data


Try making arbitrary data either:
o Predictable reference data by managing the time of validity.
o Personal data by assigning ownership (i.e. reducing the chance of
concurrent updates).

3. Observe and implement the implication of nested transactions.


Actions on unprotected objects.
Protected actions which may be undone or redone.
Real actions which may be deferred but not undone.
Nested transactions which may be undone by invoking compensating
transaction.

53

Nested transactions have several important features:

When a program starts a new transaction, if it already inside of an existing


transaction then a sub transaction is started otherwise a new top level
transaction is started.

There does not need to be a limit on the depth of transaction nesting.

When a sub transaction aborts then all of its steps are undone, including any of
its sub transactions. However, this does not cause the abort of the parent
transaction; instead the parent transaction is simply notified of the abort.

When a sub transaction is executing the entities that it is updating are not
visible to other transactions or sub transactions (as per the isolation property).

When a sub transaction commits then the updated entities are made visible to
other transactions and sub transactions.

54

Program:
CLIENT
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
public class client
{

public static void main(String args[])

{
try
{
Socket s=new Socket("172.15.169.3",8080);
try
{
DataOutputStream out=new DataOutputStream(s.getOutputStream());
DataInputStream in=new DataInputStream(s.getInputStream());
out.writeInt(25);
while(true)
{
System.out.println("=========================================");
55

System.out.println("1.Create a new Account");


System.out.println("2.Check Balance");
System.out.println("3.Withdraw");
System.out.println("4.Deposit");
System.out.println("5.Transfer");
System.out.println("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;
56

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);

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;
}
57

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();
}
58

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())
{
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;
}
}
59

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();
60

out.writeInt(tamt);
break;
case 6:
System.exit(0);
break;
default:
System.out.println("Invalid Input");
break;
}
}
}
finally
{
s.close();
}
}catch(IOException e)
{
e.printStackTrace();
}}}

SERVER
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
import java.lang.*;
61

public class server


{

public static void main(String args[])

try

ServerSocket s=new ServerSocket(8080);

while(true)
{
Socket incoming=s.accept();
Runnable r=new bankserver(incoming);
Thread t=new Thread(r);
t.start();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}}
class bankserver implements Runnable
{

private Socket incoming;

public bankserver(Socket i)
{
incoming=i;
}
public void run()
{
try
62

try

{
DataOutputStream out=new DataOutputStream(incoming.getOutputStream());
DataInputStream in=new DataInputStream(incoming.getInputStream());
System.out.println(in.readInt());
while(true)
{
int choice=in.readInt();
System.out.println("You have selected choice"+choice);
switch(choice)
{
case 1:
String name=null;
int acno1=0;
if(in.readBoolean())
{
name=in.readUTF();
acno1=in.readInt();
}
else
{
break;
}
int a=0;
try
{
63

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
Statement st=con.createStatement();
String str1="insert into parthi values('"+name+"','"+acno1+"','"+a+"')";
st.executeUpdate(str1);
}
catch(Exception e)
{
System.out.println("Account Number is already allocated");
}
break;
case 2:
int acno=in.readInt();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+acno;
System.out.println(s1);
int bal=0;
ResultSet rs=st.executeQuery(s1);
boolean check=true;
String name2=null;
while(rs.next())
{
64

name2=rs.getString(1);
bal=rs.getInt(3);
}
if(name2==null)
{
check=false;
out.writeBoolean(check);
}
else
{
out.writeBoolean(check);
out.writeInt(bal);
}
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case 3:
int acno3=in.readInt();
int amt3=in.readInt();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
65

Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+acno3;
System.out.println(s1);
int bal=0;
ResultSet rs=st.executeQuery(s1);
String name3=null;
boolean check3=true;
while(rs.next())
{

bal=rs.getInt(3);

name3=rs.getString(1);
}
if(name3== null)
{
check3=false;
}
boolean chstatus=false;
if(bal>0 && bal>amt3)
{
Object lock2=new Object();
synchronized(lock2)
{
int tmp=bal-amt3;
String s2="update parthi set balance="+tmp+" where accnumber="+acno3;
System.out.println(s2);
st.executeUpdate(s2);
chstatus=true;
66

}
}
else
{
System.out.println("Money not Ennough");
}
out.writeBoolean(check3);
if(check3==true)
{
out.writeBoolean(chstatus);
}
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case 4:
int acno4=in.readInt();
int amt4=in.readInt();
System.out.println(acno4);
System.out.println(amt4);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
67

Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+acno4;
System.out.println(s1);
String name1=null;
ResultSet rs=st.executeQuery(s1);
while(rs.next())
{
name1=rs.getString(1);
}
System.out.println(name1);
boolean ch=false;
if(name1!=null)
{
System.out.println("hai");
int actmp=0;
ResultSet rs1=st.executeQuery(s1);
while(rs1.next())
{
actmp=rs1.getInt(3);
}
System.out.println(actmp);
Object lock1=new Object();
synchronized(lock1)
{
int tmpbal=actmp+amt4;
String s2="update parthi set balance="+tmpbal+" where accnumber="+acno4;
68

System.out.println(s2);
st.executeUpdate(s2);
}
ch=true;
out.writeBoolean(ch);
}
else
{
System.out.println("nO rECORD");
out.writeBoolean(ch);
}
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case 5:
int tac1=in.readInt();
int tac2=in.readInt();
int tamt=in.readInt();
System.out.println(tac1+"

"+tac2+"

"+tamt);

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:parthi");
69

Statement st=con.createStatement();
String s1="Select * from parthi where accnumber="+tac1;
String s2="Select * from parthi where accnumber="+tac2;
System.out.println(s1);
System.out.println(s2);
ResultSet rs1=st.executeQuery(s1);
int bal1=0;
while(rs1.next())
{
bal1=rs1.getInt(3);
}
ResultSet rs2=st.executeQuery(s2);
int bal2=0;
while(rs2.next())
{
bal2=rs2.getInt(3);
}
if(bal1 < tamt)
{
}
else
{

Object lock=new Object();

synchronized(lock)
{
bal1=bal1-tamt;
bal2=bal2+tamt;
70

String s3="update parthi set balance="+bal1+" where accnumber="+tac1;


String s4="update parthi set balance="+bal2+" where accnumber="+tac2;
st.executeUpdate(s3);
st.executeUpdate(s4);
}
}}
catch(Exception e)
{

e.printStackTrace();

}
break;
case 6:
System.out.println("Client is exit");
break;
default:
System.out.println("Invalid Input from client");
break;
}
}}
catch(Exception e)
{
System.out.println("Client is Disconnected");
}
finally
{
incoming.close();
}}
71

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

OUTPUT :

72

73

74

75

Result:
Thus the given program was coded and executed successfully.
Ex.No:07
Date:12/04/10

Distributed operating systems

Aim:
To Design a RMI Lottery application.

Alorithm:
Design a superimposed computation which detects that there exists an
interleaving of underlying events in this system where at some state P ^Q
holds. (A superposed computation is one that does not a_ect the underlying
system; it may \read" but not \write" the state of the underlying system. Events
in a superposed computation may occur in at the same instant as the underlying
events and/or at di_erent instants.) State any assumptions you make.

76

Program:
LottoMad.java
import java.awt.*;
import java.net.*;
public class LottoMad1 extends java.applet.Applet
implements Runnable {
Thread playing;
// set up row 1
Panel row1 = new Panel();
CheckboxGroup option = new CheckboxGroup();
Checkbox quickpick = new Checkbox("Quick Pick", option, false);
Checkbox personal = new Checkbox("Personal",option, true);
// set up row 2
77

Panel row2 = new Panel();


Label numbersLabel = new Label("Your picks: ", Label.RIGHT);
TextField[] numbers = new TextField[6];
Label winnersLabel = new Label("Winners: ", Label.RIGHT);
TextField[] winners = new TextField[6];
// set up row 3
Panel row3 = new Panel();
Button stop = new Button("Stop");
Button play = new Button("Play");
Button reset = new Button("Reset");
// set up row 4
Panel row4 = new Panel();
Label got3Label = new Label("3 of 6: ", Label.RIGHT);
TextField got3 = new TextField("0");
Label got4Label = new Label("4 of 6: ", Label.RIGHT);
TextField got4 = new TextField("0");
Label got5Label = new Label("5 of 6: ", Label.RIGHT);
TextField got5 = new TextField("0");
Label got6Label = new Label("6 of 6: ", Label.RIGHT);
TextField got6 = new TextField("0");
Label drawingsLabel = new Label("Drawings: ", Label.RIGHT);
TextField drawings = new TextField("0");
Label yearsLabel = new Label("Years: ", Label.RIGHT);
TextField years = new TextField("0");

public void init() {


78

setBackground(Color.lightGray);
GridLayout appletLayout = new GridLayout(5, 1, 10, 10);
setLayout(appletLayout);
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(layout1);
row1.add(quickpick);
row1.add(personal);
add(row1);

GridLayout layout2 = new GridLayout(2, 7, 10, 10);


row2.setLayout(layout2);
row2.setLayout(layout2);
row2.add(numbersLabel);
for (int i = 0; i < 6; i++) {
numbers[i] = new TextField();
row2.add(numbers[i]);
}
row2.add(winnersLabel);
for (int i = 0; i < 6; i++) {
winners[i] = new TextField();
winners[i].setEditable(false);
row2.add(winners[i]);
}
add(row2);
FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row3.setLayout(layout3);
79

stop.enable(false);
reset.enable(false);
row3.add(stop);
row3.add(play);
row3.add(reset);
add(row3);

GridLayout layout4 = new GridLayout(2, 3, 20, 10);


row4.setLayout(layout4);
row4.add(got3Label);
got3.setEditable(false);
row4.add(got3);
row4.add(got4Label);
got4.setEditable(false);
row4.add(got4);
row4.add(got5Label);
got5.setEditable(false);
row4.add(got5);
row4.add(got6Label);
got6.setEditable(false);
row4.add(got6);
row4.add(drawingsLabel);
drawings.setEditable(false);
row4.add(drawings);
row4.add(yearsLabel);
years.setEditable(false);
80

row4.add(years);
add(row4);
}

public boolean action(Event event, Object object) {


if (event.target instanceof Button) {
if (event.target.equals(reset)) {
clearAllFields();
reset.enable(false);
play.enable(true);
quickpick.enable(true);
personal.enable(true);
for (int i = 0; i < 6; i++) {
numbers[i].setEditable(true);
}
}
if (event.target.equals(play)) {
playing = new Thread(this);
play.enable(false);
stop.enable(true);
reset.enable(false);
quickpick.enable(false);
personal.enable(false);
playing.start();
}
if (event.target.equals(stop)) {
81

stop.enable(false);
reset.enable(true);
quickpick.enable(false);
personal.enable(false);
for (int i = 0; i < 6; i++) {
numbers[i].setEditable(false);
}
playing.stop();
playing = null;
}
}
if (event.target instanceof Checkbox) {
if (event.target.equals(quickpick)) {
for (int i = 0; i < 6; i++) {
int pick;
do {
pick = (int)Math.floor(Math.random() * 50 + 1);
} while (numberGone(pick, numbers, i));
numbers[i].setText("" + pick);
}
} else {
for (int i = 0; i < 6; i++)
numbers[i].setText(" ");
}
}
return true;
82

void clearAllFields() {
for (int i = 0; i < 6; i++) {
numbers[i].setText("");
winners[i].setText("");
}
got3.setText("0");
got4.setText("0");
got5.setText("0");
got6.setText("0");
drawings.setText("0");
years.setText("0");
}

void addOneToField(TextField field) {


int num = Integer.parseInt(field.getText());
num++;
field.setText("" + num);
}
public void stop() {
stop.enable(false);
reset.enable(false);
play.enable(true);
quickpick.enable(true);
personal.enable(true);
83

playing.stop();
playing = null;
clearAllFields();
}
boolean numberGone(int num, TextField[] pastNums, int count) {
for (int i = 0; i < count; i++)
if (Integer.parseInt(pastNums[i].getText()) == num)
return true;
return false;
}

boolean matchedOne(TextField win, TextField[] allPicks) {


for (int i = 0; i < 6; i++) {
String winText = win.getText();
if ( winText.equals( allPicks[i].getText() ) )
return true;
}
return false;
}
public void run() {
while (true) {
addOneToField(drawings);
int draw = Integer.parseInt(drawings.getText());
float numYears = (float)draw / 104;
years.setText("" + numYears);

84

int matches = 0;
for (int i = 0; i < 6; i++) {
int ball;
do {
ball = (int)Math.floor(Math.random() * 50 + 1);
} while (numberGone(ball, winners, i));
winners[i].setText("" + ball);
if (matchedOne(winners[i], numbers))
matches++;
}
switch (matches) {
case 3:
addOneToField(got3);
break;
case 4:
addOneToField(got4);
break;
case 5:
addOneToField(got5);
break;
case 6:
addOneToField(got6);
stop.enable(false);
play.enable(true);
reset.enable(true);
playing.stop();
85

}
try { Thread.sleep(100); }
catch (InterruptedException e) {}
}
}
}

OUTPUT

86

Result:
Thus the given program was coded and executed successfully.

87

You might also like