Académique Documents
Professionnel Documents
Culture Documents
SHELL PROGRAMS
Page 1
EX.NO:1
AIM:
To write a Shell program to find the greatest of three numbers.
ALGORITHM:
Step 1:Start the program.
Step 2:Read the numbers a,b,c.
Step 3:If a is greater than b and c, print A is
greater.
Page 2
OUTPUT:
elcot@boss:~$ sh three.sh
Enter 3 numbers
2
3
4
C is Greater
RESULT
Thus the shell program for implementing greatest of three numbers
was executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 3
EX.NO:2
EVEN OR ODD
AIM:
To write a shell program to check whether the number is odd or
even.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the number a.
Step 3:Perform the modulus of that number with 2,a%2 and store it in b.
Step 4:If b=0 then print even,else print odd.
Step 5:Stop the program.
CODING:
echo "ENter a number"
read a
b='expr $a%2'
if [ $b -eq 0 ]
then
echo "Even"
else
echo "Odd"
fi
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 4
OUTPUT:
elcot@boss:~$ sh odd.sh
ENter a number
3
Odd
RESULT
Thus the shell program to find even or odd was executed
successfully and the output was verified.
Page 5
EX.NO:3
ARITHMETIC OPERATIONS
AIM:
To write a shell program to perform arithmetic operations on two
numbers.
ALGORITHM:
Step 1:Start the program.
Step 2:Read the two numbers a and b.
Step 3:Read the choice n from the user.
Step 4:If n=1,perform a+b and print result.
Step 5: If n=2,perform a-b and print result.
Step 6: If n=3,perform a*b and print result.
Step 7: If n=4,perform a/b and print result.
Step 8: If n=5,perform a%b and print result.
Step 9: Stop the program.
CODING:
echo "Arithmetic Operations"
echo "Enter two numbers"
read a
read b
echo "1.Add 2.SUb 3.Mul 4.Div 5.Mod"
echo "Enter your choice"
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 6
read n
case $n in
1)c='expr [ $a + $b ]'
echo 'Addition'$c;;
2)d='expr $a - $b'
echo 'Subtraction'$d;;
3)e='expr $a * $b'
echo 'Multiplication'$e;;
4)f='expr $a / $b'
echo 'Division'$f;;
5)g='expr $a % $b'
echo 'Modulus'$g;;
esac
OUTPUT:
elcot@boss:~$ sh air.sh
Enter two numbers
3
6
1.Add 2.SUb 3.Mul 4.Div 5.Mod
Enter your choice
1
9
RESULT:
Thus the Shell program to perform arithmetic operations on two
numbers was executed and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 7
EX.NO:4
COMBINATION OF NUMBERS
AIM:
To write a Shell program to find the combination of two numbers.
ALGORITHM:
Step 1:Start the program
Step 2:Read three numbers a,b,c.
Step 3:In for loop,for i in a,b,c do step 4.
Step 4: In for loop,for k in a,b,c do step 5.
Step 5: Display the value of i,j,k .Go back to step 3.
Step 6:Stop the program.
Page 8
CODING:
echo "Combination of Numbers"
echo Enter 3 numbers
read x
read y
read z
for i in $x $y $z
do
echo $i
for j in $x $y $z
do
echo $i $j
for k in $x $y $z
do
echo $i $j $k
done
done
done
Page 9
OUTPUT:
Page 10
RESULT:
Thus the Shell program to find the combination of two numbers
was executed and the output was verified.
Page 11
EX.NO:5
FIBONACCI SERIES
Aim:
To write a Shell program to generate Fibonacci series.
Algorithm:
Step 1: Start the program.
Step 2: Read the numbers that is n.
Step 3: Initialise a=-1,b=1,fib=0 and i=0.
Step 4: If i<n,then repeat step 4 else goto step 5.
Step 5: fib=a+b
i =i+1
Display the Fibonacci series.
Initialise a=b & b=fib.
Step 6: Stop the program.
Page 12
CODING:
echo "Enter the value"
read n
a=-1
b=1
fib=0
i=1
echo "fibonacci series"
while [ $i -le $n ]
do
fib=$((a+b))
i=$((i+1))
echo $fib
a=$b
b=$fib
done
Page 13
OUTPUT:
RESULT:
Thus the Shell program to generate Fibonacci series was executed
and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 14
EX.NO:6
MULTIPLICATION TABLE
AIM:
To write a shell program to display the multiplication table.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the number of which multiplication table is to be displayed
n.
Step 3: If (i<j) then repeat Step 5 else goto step 6
Step 4:Initialise i=1,j=0.
Step 5: Compute ans=a*i and Print the result as a*i=ans.
Step 6: Increment the value of i.
Step 7: Stop the program.
Page 15
CODING:
echo "Enter a number"
read j
echo "enter the row"
read n
i=1
a=0
while [ $i -le $n ]
do
a=`expr $i \* $j`
echo $i "*" $j "=" $a
i=`expr $i + 1`
done
Page 16
OUTPUT:
RESULT:
Thus the Shell program to display multiplication table was
executed and the output was verified.
Page 17
EX.NO:7
PALINDROME
AIM:
To write a Shell program to check whether a string is a palindrome
or not.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the string to str.
Step 3: Perform reverse operation of the string.
Step 4: Compare the string and reverse it.
Step 5: If str=x,string and reverse are equal then print It is a
palindrome or Not a palindrome.
Step 6: Stop the program.
Page 18
CODING:
echo "Enter the string"
read str
echo $str|cat>s
rev s
x=`rev s`
if [ $str = $x ]
then
echo "The give string is palindrome"
else
echo "The given string is not a palindrome"
fi
Page 19
OUTPUT:
RESULT:
Thus the Shell program to check whether a string is a palindrome
or not was executed and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 20
EX.NO: 8
SORTING
AIM:
To write a Shell program to sort the numbers.
ALGORITHM:
Step 1: Start the program.
Step 2: Allow the user to enter an option.
Step 3: Read the option to a.
Step 4: If a=1,then sort the numbers.
Step 5: If a=2,then sort the names.
Step 6: Stop the program.
Page 21
CODING:
echo "Enter your option"
echo "1.Numbers 2.Names"
read a
case $a in
1) sort -nr shell;;
2) sort -nf shell;;
esac
OUTPUT:
RESULT:
Thus the Shell program to sort numbers was executed and the
output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 22
EX.NO:9
EMPLOYEE DETAILS
AIM:
To write a Shell program to display the employee details.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the number of employees n.
Step 3: Initialise a to 1.
Step 4: If a is less than n,then do step 5 to 10
Step 5: Read the employee name,salary,DA,HRA.
Step 6: Calculate HGP=salary +HRA+DA
Step 7: Display GP.
Step 8: Read Pf and calculate p=gp-pf.
Step 9: Display name,salary,DA,HRA,GP,NP
Step 10: Increment a=a+1.
Step 11: Stop the program.
Page 23
CODING:
echo employee details
echo enter the name
read a
read a1
read a2
echo enter the emp no
read b
read b1
read b2
echo enter the salary
read c
read c1
read c2
shop=600
rent=300
pf=100
gp=`expr $c \- $shop \- $rent`
gp1=`expr $c1 \- $shop \- $rent`
Page 24
Page 25
OUTPUT:
RESULT:
Thus the Shell program to display the employee details was
executed and the output was verified.
Page 26
SCHEDULING ALGORITHMS
Page 27
EX.NO:10
ROUND-ROBIN SCHEDULING
AIM:
To write a C program to implement Round Robin scheduling.
ALGORITHM:
Step-1: Start the program
Step-2: Read the number of process n.
Step-3: Read the quantum time q.
Step-4: Read the process name and burst time.
Step-5: Initialize i=0, and while i>n, do step-6.
Step-6: Check if bt[i]%q==0,temp[i=bt[i]/q otherwise
tem[i=bt[i]/q+1
Step-7: if tem[i]>tem[0] then swap tem[0] and tem[i]
Step-8: Print the process, burst time and waiting time.
Step-9: Stop the program.
Page 28
CODING
#include<stdio.h>
int main()
{
inti,n,q,j,k=0,bt[100],qq,tm[100],time[100],tt[100],tem[100];
char p[20][10];
staticintgann[100],tmp;
floatawtm,atrt,wtm=0,trt=0;
printf("\nenter no of processes");
scanf("%d",&n);
printf("\nenter quantum time of process");
scanf("%d",&q);
for(i=0;i<n;i++)
{
printf("\nenter process name");
scanf("%s",p[i]);
printf("\nenter burst time");
scanf("%d",&bt[i]);
time[i]=bt[i];
}
for(i=0;i<n;i++)
{
if((bt[i]%q)==0)
tem[i]=(bt[i]/q);
else
tem[i]=(bt[i]/q)+1;
}
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 29
for(i=0;i<n;i++)
{
if(tem[i]>tem[0])
{
tmp=tem[0];
tem[0]=tem[i];
tem[i]=tmp;
}
}
for(i=1;i<=tem[0];i++)
{
for(j=0;j<n;j++)
{
if(bt[j]!=0)
{
if(bt[j]>=q)
{
gann[k+1]=gann[k]+q;
bt[j]=bt[j]-q;
if(bt[j]==0)
{
tm[j]=gann[k+1]-time[j];
tt[j]=gann[k+1];
}
}
else
{
gann[k+1]=gann[k]+bt[j];
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 30
bt[j]=0;
tt[j]=gann[k+1];
tm[j]=gann[k+1]-time[j];
}
k++;
}
}
}
printf("\nprocess\tburst time\twaiting time\t turn around time\n");
for(i=0;i<n;i++)
{
printf("\t%s\t%d\t%d\t%d\n",p[i],time[i],tm[i],tt[i]);
wtm=wtm+tm[i];
trt=trt+tt[i];
printf("\n");
}
awtm=wtm/n;
atrt=trt/n;
printf("\navg waiting time%f",awtm);
printf("\navg turn around time%f",atrt);
return 0;
}
Page 31
OUTPUT:
RESULT:
Thus the c program for implementing round robin algorithm was
executed and the output was verified.
Page 32
EX.NO:11
PRIORITY SCHEDULING
AIM:
To write a C program to implement priority scheduling.
ALGORITHM:
Step 1: Start the program
Step 2: Initialize a[10],pr[10],bt[10],I,j,t,temp,n,t1=0,float awt,x.
Step 3: Get the values for burst time for process priority for process
Step 4: Check for the condition pr[i] is less than pr[j].
Step 5 : Then initialize t=bt[i],temp =pr[i],bt[i]=bt[j],pt[i]=pr[j]
,bt[t] and pr[j]=temp.
Step 6 : Print the waiting time, average waiting time, turn around
time for process and the average turn around time.
Step 7: Stop the program.
Page 33
CODING
#include<stdio.h>
int main()
{
int a[10],pr[7],bt[10],i,j,t,temp,n,wt[10],t1=0;
floatawt,x;
printf("enter the no of process");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nenter the burst time for process %d",i);
scanf("%d",&bt[i]);
printf("enter the priority for process %d",i);
scanf("%d",&pr[i]);
}
printf("burst time\t\tpriority");
for(i=1;i<=n;i++)
{
printf("\n%d\t\t\t%d",bt[i],pr[i]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(pr[i]<pr[j])
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 34
{
t=bt[i];
temp=pr[i];
bt[i]=bt[j];
pr[i]=pr[j];
bt[j]=t;
pr[j]=temp;
}
}
}
printf("\npriority scheduling");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(pr[i]<pr[j])
{
temp=pr[i];
pr[i]=pr[j];
pr[j]=temp;
}
}
}
printf("\nburst time\t\tpriority");
for(i=1;i<=n;i++)
{
printf("\n%d\t\t\t%d",bt[i],pr[i]);
}
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 35
Page 36
OUTPUT:
RESULT:
Thus the c program for implementing priority scheduling algorithm
was executed and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 37
EX.NO:12
AIM:
To write a C program to implement best fit in memory
management scheme.
ALGORITHM:
Step 1: Start the program.
Step 2:Read nb,nf,fsize[max],bsize[max],temp,I,j.
Step 3: Initialise row=10,000
Step 4: Get the values for number of blocks,size of memory
block,number of process and the size of the process.
Step 5: In for loop,initializei=1 & j=1 and if bflag[j] not equal to 1,
then perform temp=bsize[j]-fsize[i].
Step 6: If Row<temp,assignfflag[i]=j and low=temp.
Step 7: Print the process no,processsize,block no and block size.
Step 8: Stop the Program.
Page 38
CODING:
#include<stdio.h>
#define MAX 20
int main()
{
intbsize[MAX],fsize[MAX],nb,nf;
inttemp,low=10000;
staticintbflag[MAX],fflag[MAX];
inti,j;
clrscr();
printf("enter the number of blocks:");
scanf("%d",&nb);
for(i=1;i<=nb;i++)
{
printf("enter the size of memory block %d:",i);
scanf("%d",&bsize[i]);
}
printf("enter the number of process::");
scanf("%d",&nf);
for(i=1;i<=nf;i++)
{
printf("enter the size of process %d:",i);
scanf("%d",&fsize[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 39
{
if(bflag[j]!=1)
{
temp=bsize[j]-fsize[i];
if(temp>=0)
{
if(low>temp)
{
fflag[i]=j;
low=temp;
}}}}
bflag[fflag[i]]=1;
low=10000;
}
printf("\nprocess no \t process size \t block no \t block size ");
for(i=1;i<=nf;i++)
{
printf("\n\n%d\t\t%d\t\t%d\t\t%d",i,fsize[i],fflag[i],bsize[fflag[i]]);
}
return 0;
}
Page 40
OUTPUT:
RESULT:
Thus the C program for Best fit memory management was
executed and the output was verified.
Page 41
EX.NO:13
AIM:
To write a C program to implement shortest job first scheduling.
ALGORITHM:
Step 1: Start the program.
Step 2: Initialise a[10],I,j,t=0,n=temp,float,qust=0,ust[10],x.
Step 3: Get the values for number of process,burst time for process
and their corresponding waiting time.
Step 4: Check the condition whether a[i] is less than a[j],if true
Step 5: Initialise temp=a[i],a[i]=a[j],a[j]=temp.
Step 6: Waiting time w[t+1]=w[i]+a[i], avg waiting time=awt+w[i]/n.
Step 7:Print the sorted order,waiting time,waiting time of
process,average waiting time,turn around time of the process.
Step 8: Stop the program.
Page 42
CODING:
#include<stdio.h>
void main()
{
int
i,j,n,temp2,name[10],brust_time[10],start_time[10],end_time[10],wait_ti
me[10],temp,tot;
floatavg;
printf("Enter the No. of jobs:\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnterProcesss number and its burst time:\n",i);
scanf("%d%d",&name[i],&brust_time[i]);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(brust_time[i]>brust_time[j])
{
temp2=name[i];
name[i]=name[j];
name[j]=temp2;
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 43
temp=brust_time[i];
brust_time[i]=brust_time[j];
brust_time[j]=temp;
}
}
if(i==1)
{
start_time[1]=0;
end_time[1]=brust_time[1];
wait_time[1]=0;
}
else
{
start_time[i]=end_time[i-1];
end_time[i]=start_time[i]+brust_time[i];
wait_time[i]=start_time[i];
}
}
printf("\n\n Process BURST TIME \t STARTING TIME \t END TIME
\t WAIT TIME\n");
printf("\n
********************************************************\n"
);
for(i=1;i<=n;i++)
{
Page 44
Page 45
OUTPUT:
RESULT:
Thus the C program for shortest job first scheduling was executed
and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 46
EX.NO:14
PRODUCER-CONSUMER PROBLEM
AIM:
To write a C program to implement producer consumer problem.
ALGORITHM:
Step 1: Start the program.
Step 2: Read stock[100],i and ch.
Step 3: Initialize producer=-1,consumer=0.
Step 4: Perform stock[i]=i+1 and read choice.
Step 5: If ch=1,check whether producer is less than consumer, then
print item is produced else print stock already available.
Step 6: If ch=2,check whether consumer is less than or equal to
produce,then print item is consumed else print stock is not
available already.
Step 7: Stop the program.
Page 47
CODING:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int stock[100],i,ch;
int producer=-1,consumer=0;
for(i=0;i<100;i++)
stock[i]=i+1;
while(1)
{
printf("\n \n \t 1.producer \t 2.consumer\t");
printf("enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:if(producer<consumer)
printf("\n\n\t item %d produced",stock[++producer]);
else
printf("\n\nstock available already");
break;
case 2:
if(consumer<=producer)
printf("\n\n\t item %d consumed",stock[consumer++]);
else
printf("\n\nstock is not available already");
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 48
break;
default:
exit(0);
}}}
OUTPUT:
RESULT:
Thus the c program for implementing producer consumer problem
was executed and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 49
EX.NO:15
AIM:
To write a C program to implement worst fit in the memory
management scheme.
ALGORITHM:
Step 1: Start the program.
Step 2: Read I,j,mem[30],pro[30],m,temp,k,avail[5],t.
Step 3: Get the values for the size of block,size of process.
Step 4: Check the condition whether mem[t] is less than mem[j].
Step 5: If true,assign temp=mem[j],mem[j]=mem[t] and
mem[t]=temp.
Step 6: Check whether pro[i]<=mem[j] if true
Step 7: Print the process placed in memory else print process cant
be placed.
Step 8: Stop the program.
Page 50
CODING:
#include<stdio.h>
void main()
{
inti,j,mem[30],n,pro[30],m,temp,k,avail[5],t;
printf("\n enter the no of blocks :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter the size of block %d:",i+1);
scanf("%d",&mem[i]);
}
m=n;
for(j=0;j<m;j++)
{
printf("\n enter the size of process %d:",j+1);
scanf("%d",&pro[j]);
}
for(i=0;i<n-1;i++)
{
t=i;
for(j=i+1;j<n;j++)
{
if(mem[t]<mem[j])
{
temp=mem[j];
mem[j]=mem[t];
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 51
mem[t]=temp;
}
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(pro[i]<=mem[j])
{
printf("\nthe process %dk is placed in memory %dk",pro[i],mem[j]);
k=j;
mem[k]=0;
avail[i]=pro[i];
break;
}
}
}
for(i=0;i<m;i++)
{
if(pro[i]!=avail[i])
{
printf("\nthe process %dk cannot be placed ",pro[i]);
}
}
}
Page 52
OUTPUT:
RESULT:
Thus the c program for implementing worst fit was executed and
the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 53
EX.NO:16
AIM:
To write a c program to implement first fit memory management
scheme.
ALGORITHM:
Step-1: Start the program
Step-2: Declare a structure process
Step-3: Declare the variables ps,flag,size, alloc.
Step-4: Initialize i=0,np=0,n=0,j=0,k=0.
Step-5: Get the values for no of blocks , size of block, number of
process and size of process.
Step-6: Inside the for loop initialize i=1, and j=1.
Step-7: Check the condition p[i].ps is less than s[j].size.
Step-8: Then assign p[i].flag=1 and s[j].alloc=1.
Step-9: Print the process, process size and blocks.
Step-10: Stop the program.
Page 54
CODING:
#include<stdio.h>
struct process
{
intps;
int flag;
}p[50];
struct sizes
{
int size;
intalloc;
}s[5];
int main()
{
inti=0,np=0,n=0,j=0,k=0;
printf("enter the number of blocks:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter the size for block %d:",i);
scanf("%d",&s[i].size);
}
printf("\nenter the number of process ");
scanf("%d",&np);
for(i=1;i<=np;i++)
{
printf("\nenter the size of the process %d:",i);
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 55
scanf("\n%d",&p[i].ps);
}
printf("\n\t\tallocation of blocks using first fit is as follows\n");
printf("\n\t\tproces \t process size \t blocks \n");
for(i=1;i<=np;i++)
{
for(j=1;j<=n;j++)
{
if(p[i].flag!=1)
{
if(p[i].ps<=s[j].size)
{
if(!s[j].alloc)
{
p[i].flag=1;
s[j].alloc=1;
printf("\n\t\t%d\t%d\t\t%d\t",i,p[i].ps,s[j].size);
}
}
}
}
}
for(i=1;i<=np;i++)
if(p[i].flag!=1)
{
printf("\n\nsorry!!!!!!!!!!!! process %d must wait as there is no sufficient
memory",p[i].ps);
}
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 56
return 0;
}
OUTPUT:
RESULT:
Thus the c program for implementing first fit was executed and the
output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 57
EX.NO:17
AIM:
To write a c program to implement system call read.
ALGORITHM:
STEP-1: Start the program
Step-2: Declare a variable F and ch[50]
Step-3: Intialize F=open(text.txt,O_ROONLY);
Step-4: If the value of F is less than O, then print it as error else
read(I,ch,50) and then print the content in the file.
Step-5: Close the file.
Step-6: Stop the program.
CODING:
#include<stdio.h>
#include<fcntl.h>
int main()
{
int F;
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 58
charch[50];
F=open("text.txt",O_RDONLY);
if(F<0)
printf("error");
else
{
read(F,ch,50);
printf("the content is ... %s",ch);
close(F);
}
return (0);
}
OUTPUT:
RESULT
Thus the c program for implementing system call - read was
executed and the output was verified
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 59
EX.NO:18
AIM:
To write a C program to implement system call write.
ALGORITHM:
Step-1: Start the program
Step-2: Declare f1, ch[4].
Step-3: Initialize f1=open(temp.txt,O_WRONGLY);
Step-4: If f1 less than zero print error or else get the value for
content and write into the file f1.
Step-5: Close the file.
Step-6: Stop the program.
CODING:
#include<stdio.h>
#include<fcntl.h>
int main()
{
int f1;
charch[4];
f1=open("temp.txt",O_WRONLY);
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 60
if(f1<0)
printf("error");
else
{
printf("enter the content:");
scanf("%s",ch);
write(f1,ch,4);
close(f1);
}
return 0;
}
OUTPUT:
RESULT:
Thus the c program for implementing system call - write was
executed and the output was verified.
Page 61
EX.NO:19
AIM:
To write a c program to implement first come first serve
scheduling.
ALGORITHM:
Step-1: Start the program.
Step-2: Declare a[10],,n,I,t=0,wait[10], avgwait=0 and x.
Step-3: Get the values for no of process and the burst time for the
process.
Step-4: The turn around time of process is calculated using t=t+a[i]
and average turnaround time for each process is calculated
using x=(float)t/n.
Step-5: Print the waiting time by calculating wait[i+1]=wait[i]+a[i].
Step-6: Average waiting time is calculated using
avgwait=avgwait+wait[i]/n.
Step-7: Stop the program.
Page 62
CODING:
#include<stdio.h>
main()
{
intn,i,j,sum=0;
intarrv[10],ser[10],start[10];
int finish[10],wait[10],turn[10];
floatavgturn=0.0,avgwait=0.0;
start[0]=0;
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the arriwal and service time of %d process:",i+1);
scanf("%d%d",&arrv[i],&ser[i]);
}
for(i=0;i<n;i++)
{
sum=0;
for(j=0;j<i;j++)
sum=sum+ser[j];
start[i]=sum;
}
for(i=0;i<n;i++)
{
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 63
finish[i]=ser[i]+start[i];
wait[i]=start[i];
turn[i]=ser[i]+wait[i];
}
for(i=0;i<n;i++)
{
avgwait+=wait[i];
avgturn+=turn[i];
}
avgwait/=n;
avgturn/=n;
printf("\narraival service Start Finish Wait Turn\n");
for(i=0;i<n;i++)
printf("%d\t%d\t%d\t%d\t%d\t%d\n",arrv[i],ser[i],start[i],
finish[i],wait[i],turn[i]);
printf("\nAverage waiting time=%f",avgwait);
printf("\nAverage turn around time=%f",avgturn);
}
Page 64
OUTPUT:
RESULT:
Thus the c program for implementing first come first serve
algorithm was executed and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 65
COMPUTER NETWORKS
Page 66
EX.NO:1
BIT STUFFING
AIM:
To write a java program to implement bit stuffing.
ALGORITHM:
STEP 1: Start the program
STEP 2: Read the input stream of bits to string
STEP 3: Read bitwise if character is equal to 1 or 0 then continue else
stop
STEP 4: Set count=1
STEP 5: If the character read is 1,then count=count+1,else if character is
zero, then reset count=5
STEP 6: Repeat step 5 till count =5
STEP 7: If the count=5,copy the string and append 0 at the end
STEP 8: Stop the program
CODING:
import java.io.*;
public class BitStuff {
public static void main(String[] args) throws IOException {
System.out.print("Enter the binary message: ");
BufferedReader br = new BufferedReader (new
InputStreamReader(System.in));
String data = br.readLine();
String res = new String();
int counter = 0;
for(int i=0;i<data.length();i++)
{ System.out.println(data.charAt(i));
if (data.charAt(i)!='1' && data.charAt(i)!='0')
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 67
OUTPUT:
RESULT:
Thus the java program to implement bit stuffing was executed
successfully and the output was verified.
Page 68
EX.NO:2
CHARACTER STUFFING
AIM:
To write a java program to implement character stuffing.
ALGORITHM:
STEP 1: Start the program
STEP 2: Read the string of text
STEP 3: Append delest to start of the string.
STEP 4: Read the string character wise
STEP 5: If the consecutive characters d,l,e comes then append all
with the string.
STEP 6: Append DLE ETX to the end of the string
STEP 7: Stop the program.
CODING:
import java.io.*;
public class CharStuff {
public static void main(String[] args) throws IOException {
System.out.print("Enter the input: ");
BufferedReader br = new BufferedReader (new
InputStreamReader(System.in));
String data = br.readLine();
String res = "DLESTX";
int i;
for(i=0;i<data.length()-2;i++)
{
if ((data.charAt(i) == 'd' || data.charAt(i) == 'D') && (data.charAt(i+1)
== 'l' || data.charAt(i+1) == 'L') && (data.charAt(i+2) == 'e' ||
data.charAt(i+2) == 'E'))
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 69
{
res = res + "DLE";
}
res = res + data.charAt(i);
}
res = res + data.charAt(i) + data.charAt(i+1) + "DLEETX";
System.out.println("Output is: " +res);
}
}
OUTPUT:
RESULT:
Thus the java program to implement character stuffing was
executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 70
EX.NO:3
AIM:
To write a java program to perform a cyclic redundancy check.
ALGORITHM:
STEP 1: Start the program
STEP 2: Declare data, div, divisor, rem and crc
STEP 3: The no of bits and the respective bits are read
STEP 4: The no of divisor bits and their bits are read.
STEP 5: tot length is calculated by adding data bits and divisor bits -1
STEP 6: The dividend after appending 0 is obtained.
STEP 7: Dividend and remainder are appended and XOR operation is
performed.
STEP 8: Enter the CRC code of total length and divide function is
performed
STEP 9: If i==rem.length-1, no error or else an error has occurred.
STEP 10: Stop the program.
CODING:
import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int[] data;
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 71
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
System.out.println("Enter number of data bits : ");
data_bits=Integer.parseInt(br.readLine());
data=new int[data_bits];
System.out.println("Enter data bits : ");
for(int i=0; i<data_bits; i++)
data[i]=Integer.parseInt(br.readLine());
System.out.println("Enter number of bits in divisor : ");
divisor_bits=Integer.parseInt(br.readLine());
divisor=new int[divisor_bits];
System.out.println("Enter Divisor bits : ");
for(int i=0; i<divisor_bits; i++)
divisor[i]=Integer.parseInt(br.readLine());
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/*------------------ CRC GENERATION-----------------------*/
for(int i=0;i<data.length;i++)
div[i]=data[i];
System.out.print("Dividend (after appending 0's) are : ");
for(int i=0; i< div.length; i++)
System.out.print(div[i]);
System.out.println();
for(int j=0; j<div.length; j++){
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 72
rem[j] = div[j];
}
rem=divide(div, divisor, rem);
for(int i=0;i<div.length;i++)
//append dividend and ramainder
{
crc[i]=(div[i]^rem[i]);
}
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
for(int j=0; j<crc.length; j++){
rem[j] = crc[j];
}
rem=divide(crc, divisor, rem);
for(int i=0; i< rem.length; i++)
{
if(rem[i]!=0)
{
System.out.println("Error");
break;
}
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 73
if(i==rem.length-1)
System.out.println("No Error");
}
System.out.println("THANK YOU.... :)");
}
static int[] divide(int div[],int divisor[], int rem[])
{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
while(rem[cur]==0 && cur!=rem.length-1)
cur++;
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
Page 74
OUTPUT:
RESULT:
Thus the java program to perform a cyclic redundancy check was
executed successfully and the output was verified.
Page 75
EX.NO:4
AIM:
To write a java program for 2-D parity checking.
ALGORITHM:
STEP 1: Start the program
STEP 2: In a class lrc, function parity is defined.
STEP 3: In the for loop, i=0 and I is less than 8, means increment.
STEP 4: if c%2==0,a[8]=0 else a[8]=1
STEP 5: In the main function, read the array of bytes a[], b[], c[].
STEP 6: Parity function is called and XOR operation is performed
between a, b, c
STEP 7: In nested for, i=0 print a[k], if i=1 print b[k]
STEP 8: In nested for check[i] =0 XOR operation is performed between
check[i] and a[k]
STEP 9: Check bits are printed successfully.
STEP 10: Stop the program.
CODING:
//2-D Parity Checking
import java.io.*;
class lrc
{
static int[] parity(int[] a)
{
int c=0,d=0;
for(int i=0;i<8;i++)
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 76
{
if(a[i]==1)
c++;
}
if(c%2==0)
a[8]=0;
else
a[8]=1;
return a;
}
public static void main(String args[])throws Exception
{
int n,i,j,k,g;
int a[]=new int[9];
int b[]=new int[9];
int c[]=new int[9];
int d[]=new int[9];
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter first byte");
for(i=0;i<8;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("Enter second byte");
for(i=0;i<8;i++)
{
b[i]=Integer.parseInt(br.readLine());
}
System.out.println("Enter third byte");
for(i=0;i<8;i++)
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 77
{
c[i]=Integer.parseInt(br.readLine());
}
parity(a);
parity(b);
parity(c);
for(i=0;i<8;i++)
{
d[i]=(a[i]^b[i]^c[i]);
}
parity(d);
g=a[8]^b[8]^c[8];
if(g==d[8])
for(i=0;i<4;i++)
{
for(k=0;k<9;k++)
{
if(i==0)
System.out.print(a[k]);
if(i==1)
System.out.print(b[k]);
if(i==2)
System.out.print(c[k]);
if(i==3)
System.out.print(d[k]);
if(k==8)
System.out.print("\n");
}
}
System.out.println("The above data is to be transmitted");
}
}
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 78
OUTPUT:
RESULT:
Thus the java program to perform 2-D parity checking was
executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 79
EX.NO:5
AIM:
To write a client-server application for chat using TCP
ALGORITHM:
CLIENT
STEP 1:Start the program
STEP 2: To create a socket in client to server.
STEP 3: The client establishes a connection to the server.
STEP 4: The client accept the connection and to send the data from
client to server and vice versa
STEP 5:The client communicate the server to send the end of the
message
STEP 6. Stop the program.
SERVER:
STEP 1:Start the program
STEP 2: To create a socket in server to client
STEP 3: The server establishes a connection to the client.
STEP 4: The server accept the connection and to send the data from
server to client and vice versa
STEP 5:The server communicate the client to send the end of the
message
STEP 6.Stop the program.
Page 80
CODING:
Server:
import java.net.*;
import java.io.*;
public class chatserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
BufferedReader
cin=newBufferedReader(newInputStreamReader(sk.getInputStream()));
PrintStream cout=new
PrintStream(sk.getOUTPUT:Stream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE");
break;
}
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 81
cin.close();
cout.close();
stdin.close();
}
}
Client:
public class chatclient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("192.168.0.19",2000);
BufferedReader sin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
PrintStream sout=new
PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close();
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 82
stdin.close();
}
}
OUTPUT:
Page 83
RESULT:
Thus the java program to perform a client-server application for
chat using TCP was executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 84
EX.NO:6
AIM:
To write a java program to perform echo client server chat.
ALGORITHM:
Step1:Start the program.
Step2: In the Client side, the host and the port are declared.
Step 3:A message is read from the client and sent to the server.
Step 4:If the message received from the server is bye the connection is
terminated.
Step 5:In the server side, port and the server socket is declared.
Step 6: A return message is sent to the client after the message received.
Step 7: Try and catch blocks are used to handle the exceptions.
Step 8: Stop the program.
CODING:
EchoServer.java
import java.io.*;
import java.net.*;
public class EchoServer
{
public EchoServer(int portnum)
{
try
{
server = new ServerSocket(portnum);
}
catch (Exception err)
{
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 85
System.out.println(err);
}
}
public void serve()
{
try
{
while (true)
{
Socket client = server.accept();
BufferedReader r = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to
close.");
String line;
do
{
line = r.readLine();
if ( line != null )
w.println("Got: "+ line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err)
{
System.err.println(err);
}
}
Page 86
EchoClient.java
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(),
true);
BufferedReader con = new BufferedReader(new
InputStreamReader(System.in));
String line;
do
{
line = r.readLine();
if ( line != null )
System.out.println(line);
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 87
line = con.readLine();
w.println(line);
}
while ( !line.trim().equals("bye") );
}
catch (Exception err)
{
System.err.println(err);
}
}}
OUTPUT:
Page 88
RESULT:
Thus the java program to perform echo client-server chat was
executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 89
EX.NO:7
FILE TRANSFER
AIM:
To write a java program to perform file transfer.
ALGORITHM:
Step 1: Start the program.
Step 2: On the client side create a socket connection.
Step 3: Establish input stream, file output stream and buffered output
stream.
Step 4: Write into a array the required values and close the socket.
Step 5: On the server side, create a server socket.
Step 6: Establish buffered input stream, output stream.
Step 7: Write into the output stream.
Step 8: Flush the output stream.
Step 9: Close the socket.
Step 10: Stop the program.
CODING:
Server code:
import java.net.*;
import java.io.*;
public class Server {
public static void main (String [] args ) throws IOException {
ServerSocket serverSocket = new ServerSocket(15123);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
File transferFile = new File ("Document.doc");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 90
Page 91
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}
Page 92
OUTPUT:
RESULT:
Thus the java program to perform file transfer was executed
successfully and the output was verified.
Page 93
EX.NO:8
AIM:
To write a java program to perform remote command execution.
ALGORITHM:
Step 1: Start the program.
Step 2: On the client side, declare a socket.
Step 3: In a try block, establish buffered reader, inet address, output
stream, output stream writer,
buffered reader.
Step 4: Include the necessary catch blocks to handle the exceptions.
Step 5: On the server side, declare the server socket.
Step 6: In a try block, establish runtime, input stream, input stream
reader, buffered reader.
Step 7: Include the necessary catch blocks to handle exceptions.
Step 8: Stop the program.
CODING:
RemoteServer.java :
import java.io.*;
import java.net.*;
class RemoteServer
{
public static void main(String args[])
{
try
{
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 94
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
ServerSocket ss=new ServerSocket(Port);
System.out.println(" Server is Ready To Receive a Command. ");
System.out.println(" Waiting ..... ");
Socket s=ss.accept();
if(s.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
InputStream in=s.getInputStream();
OutputStream ou=s.getOutputStream();
BufferedReader buf=new BufferedReader(new InputStreamReader(in));
String cmd=buf.readLine();
PrintWriter pr=new PrintWriter(ou);
pr.println(cmd);
Runtime H=Runtime.getRuntime();
Process P=H.exec(cmd);
System.out.println(" The " + cmd + " Command is Executed
Successfully. ");
pr.flush();
pr.close();
ou.close();
in.close();
}
catch(Exception e)
{
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 95
Page 96
pr.flush();
String str=buf1.readLine();
System.out.println(" " + str + " Opened Successfully. ");
System.out.println(" The " + str + " Command is Executed Successfully.
");
pr.close();
ou.close();
in.close();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}}}
Page 97
OUTPUT:
RESULT:
Thus the java program to perform remote command execution was
executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 98
EX.NO:9
AIM:
To write a java program for domain name system.
ALGORITHM:
Step 1: Start the program.
Step 2: Inside the class server, create an object server named
datagramsocket(1309).
Step 3: Receive the datagram packet where server gets receive byte,
receive byte length.
Step 4: Send the packet using send() function.
Step 5: Inside client class create an inet address with an object 127.0.00
Step 6: Print the ip address or domain name based on the data received
from server.
Step 7: Stop the program.
CODING:
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientdns12
{
public static void main(String args[])
{
try
{
DatagramSocket client=new DatagramSocket();
InetAddress addr=InetAddress.getByName("127.0.0.1");
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 99
Page 100
{
try
{
DatagramSocket server=new DatagramSocket(1309);
while(true)
{
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
//System.out.println(s);
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String
name[]={"www.aptitudeguru.com","www.downloadcyclone.blogspot.co
m"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(ip[i]))
{
sendbyte=name[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
else if(s.equals(name[i]))
{
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 101
sendbyte=ip[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Page 102
OUTPUT:
RESULT:
Thus the java program for domain name system was executed
successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 103
EX.NO:10
AIM:
To write a java program to perform remote procedure call.
ALGORITHM:
Step 1: Start the program.
Step 2: Inside a interface that extends remote, declare the required
methods.
Step 3: On the client side, extend unicast remote and implement
calculator.
Step 4: Use the required functions and in the main function create a
function for calculatorserver.
Step 5: Use the naming.rebind()function.
Step 6: On the client side read the required values to perform operations
like addition, subtraction etc.,
Step 7: Stop the program
CODING:
import java.rmi.*;
import java.io.*;
public class CalculatorClient
{
public static void main(String args[])
{
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 104
Calculator p=(Calculator)Naming.lookup("Cal");
System.out.println("Enter fisrt number");
String strFirst=br.readLine();
System.out.println("Enter second number");
String strSecond=br.readLine();
System.out.println("Sum :
"+p.sum(Integer.parseInt(strFirst),Integer.parseInt(strSecond)));
System.out.println("Sub :
"+p.sub(Integer.parseInt(strFirst),Integer.parseInt(strSecond)));
System.out.println("Mul :
"+p.mul(Integer.parseInt(strFirst),Integer.parseInt(strSecond)));
}
catch(Exception e)
{
System.out.println("Exception occurred : "+e.getMessage());
}
}
}
Server.java:
import java.rmi.*;
import java.rmi.server.*;
public class CalculatorServer extends UnicastRemoteObject implements
Calculator
{
public CalculatorServer()throws RemoteException
{
System.out.println("Server is Instantiated");
}
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 105
Page 106
OUTPUT:
RESULT:
Thus the java program to perform remote procedure call was
executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 107
EX.NO :11
CONCURRENT SERVER
AIM:
To write a java program to execute a concurrent server using
multiple threads.
ALGORITHM:
Step 1: Start the program.
Step 2:Create a user thread class which extends Thread .
Step 3: Connect the server to multiple clients using socket.
Step 4: Server process the clients request simultaneously
Step 5: On the client side, provide the required values to perform
operations .
Step 6: Stop the program
CODING:
import java.io.*;
import java.net.*;
class ServiceThread extends Thread {
Socket conn;
Public ServiceThread(Socket c) {
super("EchoServer service thread");
conn = c;
}
public void run() {
String fromUser;
PrintWriter out = null;
BufferedReader in = null;
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 108
try {
System.out.println("Got
connection
from"+
conn.getInetAddress().getHostName());
out = new PrintWriter(conn.getOutputStream(), true);
in
=
new
BufferedReader(newInputStreamReader(conn.getInputStream()));
fromUser = in.readLine();
while (fromUser != null) {
out.println(fromUser);
fromUser = in.readLine();
}
out.close();
in.close();
conn.close();
} catch (IOException e) {
System.err.println("EchoServer socket error");
System.exit(1);
}}}
public class EchoServerConc0 {
public static void main(String[] args)throws Exception{
Socket connSock = null;
intechoPort = 8000;
@SuppressWarnings("resource")
ServerSocketserverSock = new ServerSocket(echoPort, 10);
ServiceThread serve = null;
while(true) {
connSock = serverSock.accept();
serve = new ServiceThread(connSock);
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 109
serve.start();
}}}
OUTPUT:
RESULT:
Thus the java program to execute concurrent server using multiple
threads was executed successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 110
EX.NO:12
TRACE ROUTE
AIM:
To write a java program to find out the path that packets take to get
from the local machine to a destination using trace route.
ALGORITHM:
Step 1: Start the program.
Step 2:Create sockets for the connections.
Step 3: Bind the sockets and send some packets..
Step 4: Get the intermediate hosts' IP addresses.
Step 5: Turn the IP addresses into hostnames and print the data.
Step 6: Stop the program
CODING:
import java.io.*;
import java.net.*;
class trace{
public static void main(String args[])
{
String ip="www.google.com";
String pingresult="";
String pingcmd="tracert "+ip;
try{
Runtime r=Runtime.getRuntime();
Process p=r.exec(pingcmd);
BufferedReader in=new BufferedReader(new
InputStreamReader(p.getInputStream()));
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 111
String inputLine;
while((inputLine=in.readLine())!=null)
{
System.out.println(inputLine);
pingresult+=inputLine;
}
in.close();
}
catch(Exception e)
{
System.out.println(e);
} }}
Page 112
OUTPUT:
RESULT:
Thus the java program to find out the path that packets take to get
from the local machine to a destination using trace route was executed
successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 113
EX.NO:13
PING
AIM:
To write a java program to ping with an ip address.
ALGORITHM:
Step 1: Start the program.
Step 2:Create sockets for the connections.
Step 3: Bind the sockets and send some packets.
Step 4: Get the intermediate hosts' IP addresses.
Step 5: Turn the IP addresses into hostnames and print the data.
Step 6: Stop the program.
CODING:
import java.io.*;
import java.net.*;
class pingtest{
public static void main(String args[])
{
String ip="150.150.25.78";
String pingresult="";
String pingcmd="ping -t "+ip;
try{
Runtime r=Runtime.getRuntime();
Process p=r.exec(pingcmd);
BufferedReader in=new BufferedReader(new
InputStreamReader(p.getInputStream()));
String inputLine;
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 114
while((inputLine=in.readLine())!=null)
{
System.out.println(inputLine);
pingresult+=inputLine;
}
in.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
RESULT:
Thus the java program ping with an ip address was executed
successfully and the output was verified.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 115
STUDY EXPERIMENT
Page 116
Page 117
UDP Length field shows the length of the datagram in octets. It includes
the 8-byte header and the data to be sent. The UDP checksum field
contains the UDP header, UDP data and the pseudo-header shown
above. The pseudo-header contains the 32-bit IP addresses of the source
and destination machines, the UDP protocol number and the byte count
for the UDP segment. The pseudo-header helps to find undelivered
packets or packets that arrive at the wrong address. However the pseudoheader violates the protocol hierarchy because the IP addresses which
are used in it belong to the IP layer and not to the UDP layer.
UDP LATENCY
While TCP implements a form of flow control to stop the network
from flooding there is no such concept in UDP. This is because UDP
does not rely on acknowledgements to signal successful delivery of data.
Packets are simply transmitted one after another with complete disregard
to event of the receiver being flooded.
THE EFFECTS OF UDP
As mentioned before the majority of the traffic on the Internet
relies on TCP. With the explosive increase in the amount of gaming
taking place on the Internet, and with most of these games using UDP,
there are concerns about the effects that UDP will have on TCP traffic.
A study carried out in the University of Waikato in New Zealand
suggests that UDP traffic has a negative effect on TCP throughput. UDP
is now seen as being aggressive to 'network friendly applications
deploying adaptive congestion control'. While TCP implements a form
of flow control to stop the network from flooding there is no such
concept in UDP. This is because UDP does not rely on
acknowledgements to signal successful delivery of data. Packets are
simply transmitted one after another with complete disregard to event of
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 118
the receiver being flooded. UDP affects TCP throughput in much the
same way as digitized speech over IP does. The study shows that UDP
behaves in much the same way regardless of what application is running
it. UDP Broadcast Flooding A broadcast is a data packet that is destined
for multiple hosts. Broadcasts can occur at the data link layer and the
network layer. Data-link broadcasts are sent to all hosts attached to a
particular physical network. Network layer broadcasts are sent to all
hosts attached to a particular logical network. The Transmission Control
Protocol/Internet Protocol (TCP/IP) supports the following types of
broadcast packets:
All onesBy setting the broadcast address to all
(255.255.255.255), all hosts on the network receive the broadcast.
ones
Page 119
Page 120
Page 121
Page 122
Page 123
Page 124
interface on which the broadcast was received. The spanning tree also
prevents packet duplication by placing certain interfaces in the blocked
state (so that no packets are forwarded) and other interfaces in the
forwarding state (so that packets that need to be forwarded are
forwarded).
To enable UDP flooding, the router must be running software that
supports transparent bridging and bridging must be configured on each
interface that is to participate in the flooding. If bridging is not
configured for an interface, the interface will receive broadcasts, but the
router will not forward those broadcasts and will not use that interface as
a destination for sending broadcasts received on a different interface.
Note:
Releases prior to Cisco Internetwork Operating System (Cisco
IOS) Software Release 10.2 do not support flooding subnet broadcasts.
When configured for UPD flooding, the router uses the destination
address specified by the ip broadcast-address command on the output
interface to assign a destination address to a flooded UDP datagram.
Thus, the destination address might change as the datagram propagates
through the network. The source address, however, does not change.
With UDP flooding, both routers use a spanning tree to control the
network topology for the purpose of forwarding broadcasts. The key
commands for enabling UDP flooding are as follows: bridge group
protocol protocolip forward-protocol spanning tree bridge-group group
input-type-list access-list-number
INTERNETWORKING CASE STUDIES
The bridge protocol command can specify either the dec keyword
(for the DEC spanning-tree protocol) or the IEEE keyword (for the
IEEE Ethernet protocol). All routers in the network must enable the
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 125
Page 126
Page 127
Page 128
Page 129
passed to the network for delivery. This TCP header has numerous fields
that are used to support the intended TCP functionality. TCP has the
following functional characteristics:
Page 130
Page 131
Page 132
Page 133
Page 134
sequence number space of the remote side for this session. The operation
of the connection is as follows:
The local system sends the remote end an initial sequence number
to the remote port, using a SYN packet.
Page 135
Page 136
Page 137
Page 138
Page 139
The 16-bit field within the TCP header can contain values up to
65,535, imposing an upper limit on the available window size of 65,535
bytes. This imposes an upper limit on TCP performance of some 64 KB
per RTT, even when both end systems have arbitrarily large send and
receive buffers. This limit can be modified by the use of a window-scale
option, described in RFC 1323, effectively increasing the size of the
window to a 30-bit field, but transmitting only the most significant 16
bits of the value.
This allows the sender and receiver to use buffer sizes that can
operate efficiently at speeds that encompass most of the current veryhigh-speed network transmission technologies across distances of the
scale of the terrestrial intercontinental cable systems. Although the
maximum window size and the RTT together determine the maximum
achievable data-transfer rate, there is an additional element of flow
control required for TCP. If a TCP session commenced by injecting a
full window of data into the network, then there is a strong probability
that much of the initial burst of data would be lost because of transient
congestion, particularly if a large window is being used. Instead, TCP
adopts a more conservative approach by starting with a modest amount
of data that has a high probability of successful transmission, and then
probing the network with increasing amounts of data for as long as the
network does not show signs of congestion. When congestion is
experienced, the sending rate is dropped and the probing for additional
capacity is resumed. The dynamic operation of the window is a critical
component of TCP performance for volume transfer. The mechanics of
the protocol involve an additional overriding modifier of the sender's
window, the congestion window , referred to as cwnd . The objective of
the window-management algorithm is to start transmitting at a rate that
has a very low probability of packet loss, then to increase the rate (by
increasing the cwnd size) until the sender receives an indication, through
the detection of packet loss, that the rate has exceeded the available
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 140
capacity of the network. The sender then immediately halves its sending
rate by reducing the value of cwnd , and resumes a gradual increase of
the sending rate. The goal is to continually modify the sending rate such
that it oscillates around the true value of available network capacity.
This oscillation enables a dynamic adjustment that automatically
senses any increase or decrease in available capacity through the lifetime
of the data flow. The intended outcome is that of a dynamically
adjusting cooperative data flow, where a combination of such flows
behaves fairly, in that each flow obtains essentially a fair share of the
network, and so that close to maximal use of available network
resources is made. This flow-control functionality is achieved through a
combination of cwnd value management and packet-loss and
retransmission algorithms. TCP flow control has three major parts: the
flow-control modes of Slow Start and Congestion Avoidance, and the
response to packet loss that determines how TCP switches between these
two modes of operation.
TCP SLOW START
The starting value of the cwnd window (the Initial Window, or IW)
is set to that of the Sender Maximum Segment Size (SMSS) value. This
SMSS value is based on the receiver's maximum segment size, obtained
during the SYN handshake, the discovered path MTU (if used), the
MTU of the sending interface, or, in the absence of other information,
536 bytes. The sender then enters a flow-control mode termed Slow
Start.
The sender sends a single data segment, and because the window is
now full, it then awaits the corresponding ACK. When the ACK is
received, the sender increases its window by increasing the value of
cwnd by the value of SMSS. This then allows the sender to transmit two
segments; at that point, the congestion window is again full, and the
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 141
sender must await the corresponding ACKs for these segments. This
algorithm continues by increasing the value of cwnd (and,
correspondingly, opening the size of the congestion window) by one
SMSS for every ACK received that acknowledges new data. If the
receiver is sending an ACK for every packet, the effect of this algorithm
is that the data rate of the sender doubles every round-trip time interval.
If the receiver supports delayed ACKs, the rate of increase will be
slightly lower, but nevertheless the rate will increase by a minimum of
one SMSS each round-trip time. Obviously, this cannot be sustained
indefinitely. Either the value of cwnd will exceed the advertised receive
window or the sender's window, or the capacity of the network will be
exceeded, in which case packets will be lost.
There is another limit to the slow-start rate increase, maintained in
a variable termed ssthresh , or Slow-Start Threshold . If the value of
cwnd increases past the value of ssthresh, the TCP flow-control mode is
changed from Slow Start to congestion avoidance. Initially the value of
ssthresh is set to the receiver's maximum window size. However, when
congestion is noted, ssthresh is set to half the current window size,
providing TCP with a memory of the point where the onset of network
congestion may be anticipated in future.
One aspect to highlight concerns the interaction of the slow-start
algorithm with high capacity long-delay networks, the so-called Long
Fat Networks (or LFNs, pronounced "elephants"). The behavior of the
slow-start algorithm is to send a single packet, await an ACK, then send
two packets, and await the corresponding ACKs, and so on. The TCP
activity on LFNs tends to cluster at each epoch of the round-trip time,
with a quiet period that follows after the available window of data has
been transmitted. The received ACKs arrive back at the sender with an
inter-ACK spacing that is equivalent to the data rate of the bottleneck
point on the network path. During Slow Start , the sender transmits at a
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 142
rate equal to twice this bottleneck rate. The rate adaptation function that
must occur within the network takes place in the router at the entrance to
the bottleneck point. The sender's packets arrive at this router at twice
the rate of egress from the router, and the router stores the overflow
within its internal buffer. When this buffer overflows, packets will be
dropped, and the slow-start phase is over.
The important conclusion is that the sender will stop increasing its
data rate when there is buffer exhaustion, a condition that may not be the
same as reaching the true available data rate. If the router has a buffer
capacity considerably less than the delay-bandwidth product of the
egress circuit, the two values are certainly not the same.
In this case, the TCP slow-start algorithm will finish with a
sending rate that is well below the actual available capacity. The
efficient operation of TCP, particularly in LFNs, is critically reliant on
adequately large buffers within the network routers. Another aspect of
Slow Start is the choice of a single segment as the initial sending
window. Experimentation indicates that an initial value of up to four
segments can allow for a more efficient session startup, particularly for
those short-duration TCP sessions so prevalent with Web fetches.
Observation of Web traffic indicates an average Web data transfer of 17
segments. A slow start from one segment will take five RTT intervals to
transfer this data, while using an initial value of four will reduce the
transfer time to three RTT intervals. However, four segments may be too
many when using low-speed links with limited buffers, so a more robust
approach is to use an initial value of no more than two segments to
commence Slow Start .
Page 143
PACKET LOSS
Slow Start attempts to start a TCP session at a rate the network can
support and then continually increase the rate.
How does TCP know when to stop this increase? This slow start
rate increase stops when the congestion window exceeds the receiver's
advertised window, when the rate exceeds the remembered value of the
onset of congestion as recorded in ssthresh, or when the rate is greater
than the network can sustain.
Addressing the last condition, how does a TCP sender know that it
is sending at a rate greater than the network can sustain? The answer is
that this is shown by data packets being dropped by the network. In this
case, TCP has to undertake many functions:
The packet loss has to be detected by the sender.
The missing data has to be retransmitted.
The sending data rate should be adjusted to reduce the probability
of further packet loss.
TCP can detect packet loss in two ways. First, if a single packet is lost
within a sequence of packets, the successful delivery packets following
the lost packet will cause the receiver to generate a duplicate ACK for
each successive packet The reception of these duplicate ACKs is a signal
of such packet loss. Second, if a packet is lost at the end of a sequence of
sent packets, there are no following packets to generate duplicate ACKs.
In this case, there are no corresponding ACKs for this packet, and the
sender's retransmit timer will expire and the sender will assume packet
loss. A single duplicate ACK is not a reliable signal of packet loss.
When a TCP receiver gets a data packet with an out-of-order TCP
sequence value, the receiver must generate an immediate ACK of the
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 144
Page 145
Page 146
CONGESTION AVOIDANCE
Compared to Slow Start , congestion avoidance is a more tentative
probing of the network to discover the point of threshold of packet loss.
Where Slow Start uses an exponential increase in the sending rate to find
a first-level approximation of the loss threshold, congestion avoidance
uses a linear growth function. When the value of cwnd is greater than
ssthresh , the sender increments the value of cwnd by the value SMSS X
SMSS/cwnd , in response to each received non duplicate ACK , ensuring
that the congestion window opens by one segment within each RTT time
interval.
The congestion window continues to open in this fashion until
packet loss occurs. If the packet loss is isolated to a single packet within
a packet sequence, the resultant duplicate ACKs will trigger the sender
to halve the sending rate and continue a linear growth of the congestion
window from this new point, as described above in fast recovery. The
behavior of cwnd in an idealized configuration .The overall
characteristics of the TCP algorithm are an initial relatively fast scan of
the network capacity to establish the approximate bounds of maximal
efficiency, followed by a cyclic mode of adaptive behavior that reacts
quickly to congestion, and then slowly increases the sending rate across
the area of maximal transfer efficiency.
Packet loss, as signaled by the triggering of the retransmission
timer, causes the sender to recommence slow-start mode, following a
timeout interval. The inefficiency of this mode of performance is caused
by the complete cessation of any form of flow signaling from the
receiver to the sender. In the absence of any information, the sender can
only assume that the network is heavily congested, and so must restart
its probing of the network capacity with an initial congestion window of
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 147
Page 148
Page 149
been selected, the router may mark the CE bit of the packet if the ECT
bit is set; otherwise, it will discard the selected packet.
The TCP interaction is slightly more involved. The initial TCP
SYN handshake includes the addition of ECN-echo capability and
Congestion Window Reduced (CWR) capability flags to allow each
system to negotiate with its peer as to whether it will properly handle
packets with the CE bit set during the data transfer. The sender sets the
ECT bit in all packets sent. If the sender receives a TCP packet with the
ECN-echo flag set in the TCP header, the sender will adjust its
congestion window as if it had undergone fast recovery from a single
lost packet. The next sent packet will set the TCP CWR flag, to indicate
to the receiver that it has reacted to the congestion. The additional caveat
is that the sender will react in this way at most once every RTT interval.
Further, TCP packets with the ECN-echo flag set will have no further
effect on the sender within the same RTT interval. The receiver will set
the ECN-echo flag in all packets when it receives a packet with the CE
bit set. This will continue until it receives a packet with the CWR bit set,
indicating that the sender has reacted to the congestion. The ECT flag is
set only in packets that contain a data payload. TCP ACK packets that
contain no data payload should be sent with the ECT bit clear.
The connection does not have to await the reception of three
duplicate ACKs to detect the congestion condition. Instead, the receiver
is notified of the incipient congestion condition through the explicit
setting of a notification bit, which is in turn echoed back to the sender in
the corresponding ACK. Simulations of ECN using a RED marking
function indicate slightly superior throughput in comparison to
configuring RED as a packet-discard function.
However, widespread deployment of ECN is not considered likely
in the near future, at least in the context of Version 4 of IP. At this stage,
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 150
there has been no explicit standardization of the field within the IPv4
header to carry this information, and the deployment base of IP is now
so wide that any modifications to the semantics of fields in the IPv4
header would need to be very carefully considered to ensure that the
changed field interpretation did not exercise some malformed behavior
in older versions of the TCP stack or in older router software
implementations.
ECN provides some level of performance improvement over a
packet-drop RED scheme. With large bulk data transfers, the
improvement is moderate, based on the difference between the packet
retransmission and congestion-window adjustment of RED and the
congestion-window adjustment of ECN. The most notable
improvements indicated in ECN simulation experiments occur with
short TCP transactions (commonly seen in Web transactions), where a
RED packet drop of the initial data packet may cause a six-second
retransmit delay. Comparatively, the ECN approach allows the transfer
to proceed without this lengthy delay.
The major issue with ECN is the need to change the operation of
both the routers and the TCP software stacks to accommodate the
operation of ECN. While the ECN proposal is carefully constructed to
allow an essentially uncoordinated introduction into the Internet without
negative side effects, the effectiveness of ECN in improving overall
network throughput will be apparent only after this approach has been
widely adopted. As the Internet grows, its inertial mass generates a
natural resistance to further technological change; therefore, it may be
some years before ECN is widely adopted in both host software and
Internet routing systems. RED, on the other hand, has had a more rapid
introduction to the Internet, because it requires only a local modification
to router behavior, and relies on existing TCP behavior to react to the
packet drop.
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 151
TUNING TCP
How can the host optimize its TCP stack for optimum
performance? Many recommendations can be considered. The following
suggestions are a combination of those measures that have been well
studied and are known to improve TCP performance, and those that
appear to be highly productive areas of further research and
investigation
.
Use a good TCP protocol stack : Many of the performance
pathologies that exist in the network today are not necessarily the
byproduct of oversubscribed networks and consequent congestion.
Many of these performance pathologies exist because of poor
implementations of TCP flow-control algorithms; inadequate
buffers within the receiver; poor (or no) use of path-MTU
discovery; no support for fast-retransmit flow recovery, no use of
window scaling and SACK, imprecise use of protocol-required
timers, and very coarse-grained timers. It is unclear whether
network ingress-imposed Quality-of-Service (QoS) structures will
adequately compensate for such implementation deficiencies. The
conclusion is that attempting to address the symptoms is not the
same as curing the disease. A good protocol stack can produce
even better results in the right environment.
Implement a TCP Selective Acknowledgment (SACK) mechanism
: SACK, combined with a selective repeat-transmission policy, can
help overcome the limitation that traditional TCP experiences
when a sender can learn only about a single lost packet per RTT.
Implement larger buffers with TCP window-scaling options : The
TCP flow algorithm attempts to work at a data rate that is the
minimum of the delay bandwidth product of the end-to-end
network path and the available buffer space of the sender. Larger
buffers at the sender and the receiver assist the sender in adapting
12CS2406- OPERATING SYSTEMS AND COMPUTER NETWORK LABORATORY
Page 152
Page 153
CONCLUSION
TCP is not a predictive protocol. It is an adaptive protocol that
attempts to operate the network at the point of greatest efficiency.
Tuning TCP is not a case of making TCP pass more packets into the
network. Tuning TCP involves recognizing how TCP senses current
network load conditions, working through the inevitable compromise
between making TCP highly sensitive to transient network conditions,
and making TCP resilient to what can be regarded as noise signals. If the
performance of end-to-end TCP is the perceived problem, the most
effective answer is not necessarily to add QoS service differentiation
into the network. Often, the greatest performance improvement can be
made by upgrading the way that hosts and the network interact through
the appropriate configuration of the host TCP stacks. In the next article
on this topic, we will examine how TCP is facing new challenges with
increasing use of wireless, short-lived connections, and bandwidthlimited mobile devices, as well as the continuing effort for improved
TCP performance. We'll look at a number of proposals to change the
standard actions of TCP to meet these various requirements and how
they would interact with the existing TCP.
Page 154