You are on page 1of 50

PROGRAM 1

DISTRIBUTED SYSTEM RESOURCE SHARING


Distributed system is one in which hardware and software components located at
networked computers communicate and coordinate their actions only by passing
messages.

RESOURCE SHARING

Sharing of resources on a same network. We generally share hardware components such


as printers, data resources such as files, and resources with more specific functionally
such as search engines. There are three types of resource sharing

• Sharing of data

• Sharing of device

• Sharing of drive

For Resource Sharing we should get permission of some administrator

SHARING OF DATA

Steps to Share data

• Create new folder on desktop


• Name that folder , now right click on that folder choose option sharing and
security

• After clicking on sharing and security ,small window will open there check that
box where is written Share this folder on the network then click Apply and then
OK
• After these steps folder will look like this as shown Below

It means folder is shared.


SHARING OF DRIVE

Steps for Sharing of drive are:

• Choose one drive as drive D ,Right click on it choose option sharing and
security then window will open as shown below click on that blue line
then apply and then ok

• After that new window will open again as shown below

Now, check that box where is written share this folder on the network

Then Apply and OK


• Folder will look like this as shown below after completing above steps

This means drive is shared


SHARING OF DEVICE
For sharing of drive following steps are followed

• Go in the run option write IP address of that system where device is connected ex:
printer then enter, window will open of that system. Now right click on the name
of printer choose option connect then window will open as shown below

Click OK

• Go on start menu choose printers and faxes


• After clicking on printers and faxes window will open as shown below
Now right click on Microsoft XPS Document Writer choose option Sharing
• After clicking shown window will open and choose option share this printer
And then Apply and then OK.

• then device will look like as shown below

This shows that device is shared


PROGRAM 2

LAMPORT’S LOGICAL CLOCK

A Lamport clock may be used to create a partial causal ordering of events between processes.
Given a logical clock following these rules, the following relation is true: if then
, where means happened-before.
This relation only goes one way, and is called clock consistency condition: if one event comes
before another, then that event's logical clock comes before the others. The strong clock
consistency condition, which is two way (if then ), can be obtained by
other techniques such as vector clocks. Using only a simple Lamport clock, only a partial causal
ordering can be inferred from the clock.
However, via the contra positive, it's true that implies . So, for example,
if then cannot have happened-before .
Another way of putting this is that means that may have happened-before ,
or be incomparable within the happened-before ordering, but did not happen after .
Nevertheless, Lamport timestamps can be used to create a total ordering of events in a distributed
system by using some arbitrary mechanism to break ties (e.g. the ID of the process). The caveat
is that this ordering is art factual and cannot be depended on to imply a causal relationship.
Two implementation rules for implementing Lamport’s Logical Clock are as follow:

IR1:-

IR1 says that a clock Ci incremented between any two successive events in process P i by the
formula

Ci=Ci+d. d>0

IR2:-

IR2 states that if event ‘a’ is a message sending event from process Pi then this message is
assigned a time stamp Tm=Ci(a). On receiving that message by process Pj, Cj is updated
according to the formula

Cj=MAX(Tm+d,Cj) d>0
Program:-
#include<stdio.h>

void main()

int p1[10],p2[10],i,j,n=0,m=0;
clrscr();

printf("the timestamp for p1");


for(i=1;i<=10;i++)

{
p1[i]=i;

printf("\n%d",p1[i]);
}

printf("\nenter the timestamp for p2");


for(j=1;j<=10;j++)

p2[j]=j;

printf("\n%d",p2[j]);
}

printf("\nwhich event of prcess p1 send the message");


scanf("%d",&n);
printf("\nwhich event of prcess p2 receive the message");

scanf("%d",&m);
p2[m]=max(p1[n]+1,p2[m]);
printf("\nthe new timestamp for p2..");
for(j=1;j<=10;j++)

if(j>m)
{

p2[j]=p2[m]+1;

m++;

}
printf("\n%d",p2[j]);

}
}

OUTPUT
PROGRAM 3

VECTOR LOGICAL CLOCK


Vector clocks is an algorithm for generating a partial ordering of events in a distributed
system and detecting causality violations. Just as in Lamport timestamps, inter-process messages
contain the state of the sending process's logical clock. A vector clock of a system of N processes
is an array/vector of N logical clocks, one clock per process; a local "smallest possible values"
copy of the global clock-array is kept in each process, with the following rules for clock updates:

• Initially all clocks are zero.


• Each time a process experiences an internal event, it increments its own logical clock in the
vector by one.
• Each time a process prepares to send a message, it sends its entire vector along with the
message being sent.
• Each time a process receives a message, it increments its own logical clock in the vector by
one and updates each element in its vector by taking the maximum of the value in its own
vector clock and the value in the vector in the received message (for every element).

Two implementation rules of vector clock are as follows:

IR1:-

IR1 says that a clock Ci incremented between any two successive events in process P i by the
formula Ci[i]=Ci[i]+d. d>0

IR2:-

IR2 states that if event ‘a’ is a message sending event from process Pi then this message is
assigned a vector time stamp Tm=Ci[a]. On receiving that message by process Pj, Cj is
updated according to the formula

For all k, Cj[k]=MAX(Tm[k],C j[k]) d>0


Program:-
#include<stdio.h>

void main()
{

int p1[10][10],p2[10][10],i,j,m=0,n=0,a=0,b=0;
clrscr();

printf("\nThe timestamp for process P1\n");

for(i=1;i<=10;i++)

p1[i][1]=i;

p1[i][2]=0;

printf("%d,%d\n",p1[i][1],p1[i][2]);

printf("\nThe timestamp for process P2\n");

for(j=1;j<=10;j++)

p2[j][2]=j;

p2[j][1]=0;
printf("%d,%d\n",p2[j][1],p2[j][2]);

}
printf("\nEnter which event want to send the message\n");
scanf("%d",&a);

printf("\nEnter which event want to receive the message\n");


scanf("%d",&b);

m=max(p1[a][1],p2[b][1]);

n=max(p1[a][2],p2[b][2]);

p2[b][1]=m;
p2[b][2]=n;
printf("\n New timesatmp is:\n");
for(j=1;j<=10;j++)

{
if(j>b)

p2[j][1]=m;

}
printf("%d,%d\n",p2[j][1],p2[j][2]);

OUTPUT
PROGRAM 4
Mutual Exclusion
Mutual exclusion, in computer science, refers to the problem of ensuring that no two processes
or threads (henceforth referred to only as processes) can be in their critical section at the same
time. Here, a critical section refers to a period of time when the process accesses a shared
resource, such as shared memory. Systems involving multiple processes are often most easily
programmed using critical regions. When a process has to read or update certain shared data
structures, it first enters a critical region to achieve mutual exclusion and ensure that no other
process will use the shared data structures at the same time.
Uses of Mutual Exclusion:-

• Prevention from deadlock.


• Prevention from starvation.
• Fairness
• Optimization

Types of Mutual Exclusion:-

1. Non-Token based:-
In this every process shares its time stamp(execution time) & process ID with all the
other processes. All process take decision which process has to be executed in its critical
section. Example: - Lamport algorithm.
2. Token based:-
In this process a token is rotated among every process and which process has this token
will entered in critical section and no other process is executed if it should not have
token. Example: - Suzuki-Kasami algorithm.

Performance Metrics of Mutual Exclusion:-

• Response Time
• Synchronization Delay
• System Throughput
• No. of messages necessary per critical section invocation.
Program:-
#include<stdio.h>

#include<dos.h>

#include<time.h>

void main()

int cs=0,pro=0;

double run=5;

char key='a';

time_t t1,t2;

clrscr();

printf("Press a key(except q) to enter a process into crirical section.\n");

printf("\nPress q at any time to exit.\n");

t1=time(NULL)-5;

while(key!='q')

while(!kbhit())

if(cs!=0)

t2=time(NULL);

if(t2-t1>run)

printf("Process %d\n",pro-1);

printf("\nExits critical section\n");

cs=0;
}

key=getch();

if(key!='q')

if(cs!=0)

printf("\nError:Another process is currently executing critical section Please wait till its
execution is over\n");

else

printf("Process %d",pro);

printf("Entered critical section\n");

cs=1;

pro++;

t1=time(NULL);

}
OUTPUT
PROGRAM 5

TCP CHAT SERVER

Introduction:-

In this article, we will discuss a chat application using asynchronous TCP sockets in java.

TCP Server:-
The server application listens on a particular port and waits for the clients. The clients
connect to the server and join the room. The client then sends a message to the server, the
server then sends this to all the users in the room.

TCPClient:-
The client firstly connects to the server:
Once connected, a login message is sent to the server. And after that, we send a list
message to get the names of clients in the chat room.
Program:-

Client.java:-
import java.net.*;
import java.io.*;
public class Client{
public static void main(String args[])throws IOException
{
Socket s=null;
BufferedReader b=null;
try
{
s=new Socket(InetAddress.getLocalHost(),98);
b=new BufferedReader(new InputStreamReader(s.getInputStream()));
}
catch(Exception e)
{
System.out.println("I do not host");
e.printStackTrace();
}
String inp;
while((inp=b.readLine())!=null){
System.out.println(inp);
}
b.close();
s.close();
}
}
Server.java:-
import java.net.*;
import java.io.*;
public class Server{
public static void main(String args[])throws IOException
{
ServerSocket s1=null;
try
{
s1=new ServerSocket(98);
}
catch(Exception e)
{
System.out.println("Port not found");
e.printStackTrace();
}
Socket c=null;
try
{
c=s1.accept();
System.out.println("Connection from"+c);
}
catch(Exception e)
{
System.out.println("not accepted");
e.printStackTrace();
}
PrintWriter out=new PrintWriter(c.getOutputStream(),true);
BufferedReader in=new BufferedReader(new
InputStreamReader(c.getInputStream()));
String l;
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("I am ready type now");
while((l=sin.readLine())!=null){
out.println(l);
}
out.close();
sin.close();
c.close();
s1.close();
}
}
Steps to Compile And Run The Program:-
1. Open CMD Screen

2. Compile the program by using command javac *.java


3. Run server program using command java Server

4. Open another CMD screen


5. Run client program using command java Client
6. Chat window between server and client
PROGRAM 6

RMI (Remote Method Invocation)

The Remote Method Invocation (RMI) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object running
in another JVM.
The RMI provides remote communication between the applications using two objects stub and
skeleton. It is a true distributed computing application interface for Java, written to provide easy
access to objects existing on remote virtual machines.

Fig :- Architecture of RMI

1. Client:-
Client is a user interface.
2. Stubs:-
The stub is an object, acts as a gateway for the client side.
3. Remote Reference:-
Remote Reference Layer provides a Remote Ref object that represents the link to the remote
service implementation object. It encodes and decodes the on-wire protocol. It implements the
remote object protocols.
4. Skeleton:-
The skeleton is an object, acts as a gateway for the server side object.
5. Server:-
It is a data source.
6. Transport Layer:- The Transport Layer makes the connection between JVMs.
Program:-
Client.java:-
importjava.rmi.*;
import java.net.*;
import java.io.*;
public class client
{
public static void main(String []args) throws Exception
{
DataInputStream ds=new DataInputStream(System.in);
String url="rmi://localhost/server";
multiply s=(multiply)Naming.lookup(url);
System.out.println("Enter two numbers::::");
String s1=ds.readLine();
String s2=ds.readLine();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
System.out.println("::Multiply of Two numbers::");
System.out.println(s.multiply(a,b));
}
}

Server.java:-
importjava.rmi.*;
importjava.rmi.server.*;
public class server extends UnicastRemoteObject implements multiply
{
public server() throws RemoteException{}
public static void main(String args[]) throws Exception
{
System.out.println("Server Started.....");
server s=new server();
Naming.bind("server",s);
}
publicint multiply(inta,int b)
{
return(a*b);
}
}

Multiply.java:-
importjava.rmi.*;
interface multiply extends Remote
{
int multiply(intx,int y) throws RemoteException;
}

Steps:-
1. Start rmiregistry at server.
2. Execute Server code at server.
3. When server is started, Execute Client code at client.
4. Give input to the program and get output which is computed remotely on server.
OUTPUT
PROGRAM 7

SIMULATION OF SLIDING WINDOW PROTOCOL


Program:-

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

int n,r;

struct frame

char ack;

int data;

}frm[10];

int sender(void);

void recvfrm(void);

void resend(void);

void resend1(void);

void goback(void);

void selective(void);
int main()

int c;

do

printf("\n\n1.Selective repeat ARQ\n2.Goback ARQ\n3.exit");

printf("\nEnter ur choice:");

scanf("%d",&c);

switch(c)

case 1: selective();

break;

case 2: goback();

break;

case 3: exit(0);

break;

}while(c!=4);

return 0;

}
void goback()

sender();

recvfrm();

resend1();

printf("\n all packets sent successfully\n");

void selective()

sender();

recvfrm();

resend();

printf("\nAll packets sent successfully");

int sender()

int i;

printf("\nEnter the no. of packets to be sent:");

scanf("%d",&n);

for(i=0;i<n;i++)

printf("\nEnter data for packets[%d]",i);

scanf("%d",&frm[i].data);
frm[i].ack='y';

return 0;

void recvfrm()

int i;

rand();

r=rand()%n;

frm[r].ack='n';

for(i=0;i<n;i++)

if(frm[i].ack=='n')

printf("\nThe packet number %d is not received\n",r);

void resend()

printf("\nresending packet %d",r);

sleep(2);

frm[r].ack='y';

printf("\nThe received packet is %d",frm[r].data);

}
void resend1()

int i;

printf("\n resending from packet %d",r);

for(i=r;i<n;i++)

sleep(2);

frm[i].ack='y';

printf("\nReceived data of parent %d is %d",i,frm[i].data);

OUTPUT
PROGRAM 8

Implementation of CORBA( Common Object Request Broker Architecture)


mechanism.

The Common Object Request Broker Architecture (CORBA) is a standard defined by


the Object Management Group (OMG) designed to facilitate the communication of systems that
are deployed on diverse platforms. CORBA enables collaboration between systems on different
operating systems, programming languages, and computing hardware. CORBA has many of the
same design goals as object-oriented programming: encapsulation and reuse. CORBA uses an
object-oriented model although the systems that utilize CORBA do not have to be object-
oriented. CORBA is an example of the distributed object paradigm.

CORBA enables software written in different languages and running on different computers to
work with each other seamlessly. Implementation details from specific operating systems,
programming languages, and hardware platforms are all removed from the responsibility of
developers who use CORBA. CORBA normalizes the method-call semantics between
application objects residing either in the same address-space (application) or in remote address-
spaces (same host, or remote host on a network).
1.FileInterface.idl

interface FileInterface {
typedef sequence<octet> Data;
Data downloadFile(in string fileName);
};

//Now, let's compile the FileInterface.idl and generate server-side skeletons. Using the
command:

idlj -fserver FileInterface.idl

2.FileServant.java

import java.io.*;

public class FileServant extends _FileInterfaceImplBase {


public byte[] downloadFile(String fileName){
File file = new File(fileName);
byte buffer[] = new byte[(int)file.length()];
try {
BufferedInputStream input = new
BufferedInputStream(new FileInputStream(fileName));
input.read(buffer,0,buffer.length);
input.close();
} catch(Exception e) {
System.out.println("FileServant Error: "+e.getMessage());
e.printStackTrace();
}
return(buffer);
}
}
3.FileServer.java

import java.io.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class FileServer {


public static void main(String args[]) {
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// create the servant and register it with the ORB
FileServant fileRef = new FileServant();
orb.connect(fileRef);
// get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Bind the object reference in naming
NameComponent nc = new NameComponent("FileTransfer", " ");
NameComponent path[] = {nc};
ncRef.rebind(path, fileRef);
System.out.println("Server started....");
// Wait for invocations from clients
java.lang.Object sync = new java.lang.Object();
synchronized(sync){
sync.wait();
}
} catch(Exception e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace(System.out);
}
}
}
4.FileClient.java

import java.io.*;
import java.util.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;

public class FileClient {


public static void main(String argv[]) {
try {
// create and initialize the ORB
ORB orb = ORB.init(argv, null);
// get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
NameComponent nc = new NameComponent("FileTransfer", " ");
// Resolve the object reference in naming
NameComponent path[] = {nc};
FileInterfaceOperations fileRef =
FileInterfaceHelper.narrow(ncRef.resolve(path));

if(argv.length < 1) {
System.out.println("Usage: java FileClient filename");
}

// save the file


File file = new File(argv[0]);
byte data[] = fileRef.downloadFile(argv[0]);
BufferedOutputStream output = new
BufferedOutputStream(new FileOutputStream(argv[0]));
output.write(data, 0, data.length);
output.flush();
output.close();
} catch(Exception e) {
System.out.println("FileClient Error: " + e.getMessage());
e.printStackTrace();
}
}
}
Running the application

1. tnameserv
2. java FileServer
3. idlj -fclient FileInterface.idl
4. java FileClient hello.txt

Output
PROGRAM 9

Telnet
Telnet is a protocol that allows you to connect to remote computers (called hosts) over a TCP/IP
network (such as the Internet). It provides a bidirectional interactive text-oriented
communication facility using a virtual terminal connection. You can make a connection to a
telnet server (i.e., the remote host). Once your telnet client establishes a connection to the remote
host, your client becomes a virtual terminal, allowing you to communicate with the remote host
from your computer. In most cases, you'll need to log into the remote host, which requires that
you have an account on that system.
Java program for Telnet sever:
import java.net.*;
import java.io.*;
import java.lang.*;
import java.io.*;
import java.util.*;
class TelnetServer
{
public static void main(String args[]) throws Exception
{
ServerSocket Soc=new ServerSocket(5217);
while(true)
{
Socket CSoc=Soc.accept();
AcceptTelnetClient ob=new AcceptTelnetClient(CSoc);
}
}
}
class AcceptTelnetClient extends Thread
{
Socket ClientSocket;
DataInputStream din;
DataOutputStream dout;
String LoginName;
String Password;
AcceptTelnetClient(Socket CSoc) throws Exception
{
ClientSocket=CSoc;
System.out.println("Client Connected ...");
DataInputStream din=new DataInputStream(ClientSocket.getInputStream());
DataOutputStream dout=new
DataOutputStream(ClientSocket.getOutputStream());
System.out.println("Waiting for UserName And Password");
LoginName=din.readUTF();
Password=din.readUTF();
start();
}
public void run()
{
try
{
DataInputStream din=new DataInputStream(ClientSocket.getInputStream());
DataOutputStream dout=new
DataOutputStream(ClientSocket.getOutputStream());
BufferedReader brFin=new BufferedReader(new FileReader("Passwords.txt"));
String LoginInfo=new String("");
boolean allow=false;
while((LoginInfo=brFin.readLine())!=null)
{
StringTokenizer st=new StringTokenizer(LoginInfo);
if(LoginName.equals(st.nextToken()) &&
Password.equals(st.nextToken()))
{
dout.writeUTF("ALLOWED");
System.out.println("Allowed");
allow=true;
break;
}
}

brFin.close();
if (allow==false)
{
dout.writeUTF("NOT_ALLOWED");
System.out.println("Not Allowed");
}
while(allow)
{
String strCommand;
strCommand=din.readUTF();
if(strCommand.equals("quit"))
{
allow=false;
}
else
{
Runtime rt=Runtime.getRuntime();
Process p=rt.exec("TelnetServer.bat " + strCommand);
String stdout=new String("");
String st;
DataInputStream dstdin=new
DataInputStream(p.getInputStream());
while((st=dstdin.readLine())!=null)
{
stdout=stdout +st + "\n";
}
dstdin.close();
dout.writeUTF(stdout);
}
}
ClientSocket.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

Java program for Telnet client:


import java.net.*;
import java.io.*;
class TelnetClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("127.0.0.1",5217);
String LoginName;
String Password;
String Command;
DataInputStream din=new DataInputStream(soc.getInputStream());
DataOutputStream dout=new DataOutputStream(soc.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Welcome to Telnet Client");
System.out.println("Your Credential Please...");
System.out.print("Login Name :");
LoginName=br.readLine();
System.out.print("Password :");
Password=br.readLine();
dout.writeUTF(LoginName);
dout.writeUTF(Password);
if (din.readUTF().equals("ALLOWED"))
{
do
{
System.out.print("< Telnet Prompt >");
Command=br.readLine();
dout.writeUTF(Command);
if(!Command.equals("quit"))
{
System.out.println(din.readUTF());
}
}while(!Command.equals("quit"));
}
soc.close();
}
}

Steps:

1. Execute Server program at server.


2. Execute Client program at client.
3. When client is connected to server. Enter username & password for login.
4. After successful login, client can access server remotely.
OUTPUT
PROGRAM 10

Implement RPC mechanism for a file transfer across a network

RPC is a powerful technique for constructing distributed, client-server based applications. It is


based on extending the notion of conventional or local procedure calling, so that the called
procedure need not exist in the same address space as the calling procedure. The two processes
may be on the same system, or they may be on different systems with a network connecting
them. By using RPC, programmers of distributed applications avoid the details of the interface
with the network. The transport independence of RPC isolates the application from the physical
and logical elements of the data communications mechanism and allows the application to use a
variety of transports.

RPC makes the client/server model of computing more powerful and easier to program. When
combined with the ONC RPCGEN protocol compiler clients transparently make remote calls
through a local procedure interface.

Sequence of events during an RPC

1. The client calls the client stub. The call is a local procedure call, with parameters pushed
on to the stack in the normal way.
2. The client stub packs the parameters into a message and makes a system call to send the
message. Packing the parameters is called marshalling.
3. The client's local operating system sends the message from the client machine to the
server machine.
4. The local operating system on the server machine passes the incoming packets to
the server stub.
5. The server stub unpacks the parameters from the message. Unpacking the parameters is
called unmarshalling.
6. Finally, the server stub calls the server procedure. The reply traces the same steps in the
reverse direction.
client.java

import java.io.*;
import java.net.*;
class Client{
public static void main(String args[]){
try{
Socket sock=new Socket (args[0],8081);
FileInputStream is=new FileInputStream("client.class");
OutputStream os=sock.getOutputStream();
int ch=0;
ch=is.read();
do{
os.write(ch);
ch=is.read();
}while(ch!=-1);
os.flush();
os.close();
sock.close();
}
catch(Exception e){System.out.println(e);}

}
server.java

import java.io.*;
import java.net.*;
class server {
public static void main(String args[]){
new server().go();
}
public void go(){
while(true){
try{
ServerSocket server=new ServerSocket(8081);
Socket socket=server.accept();
new Thread(new thread(socket)).start();
}
catch(Exception e){
}
}
}
class thread implements Runnable{
Socket s;
thread(Socket s){
this.s=s;
}
public void run(){
try{
InputStream is=s.getInputStream();
FileOutputStream out =new FileOutputStream(new File("clientcopy.class"));
int ch=0;
ch=is.read();
do{
out.write(ch);
ch=is.read();
}while(ch!=-1);
out.flush();
System.out.println("File (client.class) Copied to server as
(clientcopy.class)");
out.close();
s.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
}

You might also like