MJCET 1604-10-862-007 ASSIGNMENT-1 SHELL PROGRAMMING #1) Shell script to display the number of lines, words, #characters in each of the text file in given directory wc /root/mca11/* [root@localhost ~]#ksh wordcount Output: Displaying the number of words in the directory 6 8 61 /root/1.c 47 125 1261 /root/anaconda-ks.cfg 4 84 4668 /root/a.out 0 0 0 /root/Desktop 1259 5072 54057 /root/install.log 0 0 0 /root/install.log.syslog 0 0 0 /root/mca1107 4 25 195 /root/scsrun.log 0 0 0 /root/tmp 3 11 66 /root/wcount 1323 5355 60308 total UNIX PROGRAMMING 1 MCA II nd Year II nd Sem
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
MJCET 1604-10-862-007
ASSIGNMENT-1
SHELL PROGRAMMING
#1) Shell script to display the number of lines, words, #characters in each of the text file in given directory
wc /root/mca11/*[root@localhost ~]#ksh wordcount
Output:
Displaying the number of words in the directory 6 8 61 /root/1.c 47 125 1261 /root/anaconda-ks.cfg 4 84 4668 /root/a.out 0 0 0 /root/Desktop 1259 5072 54057 /root/install.log 0 0 0 /root/install.log.syslog 0 0 0 /root/mca1107 4 25 195 /root/scsrun.log 0 0 0 /root/tmp 3 11 66 /root/wcount 1323 5355 60308 total
UNIX PROGRAMMING 1 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 2) Shell script to rename all files whose names end #with. .c as .old (For example example.c file should be #renamed as example.old)
# 3) Shell script to concat the contents of two files into a destination file
[root@localhost ~]# vi file1print this is the contents of the first file
[root@localhost ~]# vi file2print this is the content of the second file
cat file1 file2 >file3
output:
Print this is the contents of the first fileprint this is the content of the second file
UNIX PROGRAMMING 3 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 4) Shell script to print its own name and process id
print The script name is $0print The process id is $$
output:
The script name is 4The process id is 3274
UNIX PROGRAMMING 4 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
#5) Shell script to print date in the order: time: day of #week: day: month: #year
print date in the order:time :day of the week:day:month:yeardate +%T:%A:%d:%B:%y
output:
[root@localhost ~]# ksh 5date in the order:time :day of the week:day:month:year12:46:17:Sunday:27:March:11
UNIX PROGRAMMING 5 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 6) Shell script to take any number of filename as #command line arguments and concat them into the #destination file.
for i in $*do cat $i >> tempdonecat temp
output:
[root@localhost ~]# ksh 6 file1 file3 tempprint this is the contents of the first fileprint this is the contents of the first fileprint this is the content of the second fileprint this is the contents of the first fileprint this is the contents of the first fileprint this is the content of the second file
UNIX PROGRAMMING 6 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 7) Shell script that takes file names as arguments and #checks if they are files or directories.
for i in $*do if [[ -f $i ]] then print $i is a regular file else if [[ -d $i ]] then print $i is a directory fi fidone
output:
[root@localhost ~]# ksh 7 mca1107 file1mca1107 is a directoryfile1 is a regular file
UNIX PROGRAMMING 7 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 8) Shell script to find the exit status of a command
print enter two numbersread num1 num2if(( $num1 > $num2 )) then print if condition is true exit status is $?
else print if condition is false exit status is $?fi
output:
[root@localhost ~]# ksh 8enter two numbers20 07if condition is true exit status is 0
UNIX PROGRAMMING 8 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 9) Interactive shell script to copy, remove, rename or link files
select ch in copy remove rename link exitdocase $ch in copy) print enter two file names. read file1 read file2 cp $file1 $file2 print copy completed..contents of file1 copied into file2 ;; remove) print enter the file name to remove. read file6 rm $file6 print file6 has been removed ;; rename) print enter the name of the file to rename original and new read original read new mv $original $new print The file has been renamed ;; link) print enter the names of the file to link read file1 ln $file1 /root/Desktop ;; exit) print Exiting from the menu ;;esacdone
UNIX PROGRAMMING 9 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 10) Shell script to make the calendar command interactive
print INTERACTIVE CALENDAR OPTIONSprint 1 For current monthprint 2 For current year print 3 For three months print 4 For the year.x print 5 For the x month of x yearprint 6 To exitprint Enter your choice.read chcase $ch in
1) print current month cal -1 ;;2) print current year cal -y ;;3) print previous, present and next months cal -3 ;;4) print the year for calendar read year cal $year ;;5) print enter a valid month number
read month print enter a valid year number read year cal $month $year ;;6) print Exiting....... ;;
esac
UNIX PROGRAMMING 10 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 11) Shell script to find a particular pattern in all files the current directory
print enter the pattern you want to find in all the files of the directory read pattern for i in *do if [[ -f $i ]] then grep $pattern $i fidone
output:
[root@localhost ~]# ksh 11enter the pattern you want to find in all the files of the directorycopyselect ch in copy remove rename link exit copy) print enter two file names. print copy completed..contents of file1 copied into file2 ;;
UNIX PROGRAMMING 11 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
12) Shell script to find out whether an executable file #exists in the given path or not
print enter the file nameread fileif [[ -x $file ]] then print this is exe fileelse print this is not exe filefi
output:
[root@localhost ~]# ksh 12enter the file namea.outthis is exe file
UNIX PROGRAMMING 12 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
# 13) Shell script to change the case from upper to lower #or lower to upper
print enter fileread fileprint "converting all lower to upper case letters"cat $file|tr a-z A-Zprint "converting all upper to lower case letters"cat $file|tr A-Z a-z
OUTPUT:
[root@localhost ~]# ksh 13enter fileabcconverting all lower to upper case lettersTHIS IS KORN SHELLTHIS IS KORN SHELLconverting all upper to lower case lettersthis is korn shellthis is korn shell
UNIX PROGRAMMING 13 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
#14) Shell script to implement calculator case $2 in +) (( res = $1 + $3 )) print $res;; -) (( res = $1 - $3 )) print $res;; x) (( res = $1 * $3 )) print $res;; /) (( res = $1 / $3 )) print $res;; *) print "wrong choice";;esac
# 15) Shell script to find out whether a given year is #leap year or not
print enter the yearread yearif (( year%4 == 0 )) then
print leap yearelse
print not a leap yearfi
output:
[root@localhost ~]# ksh 15enter the year1988leap year
UNIX PROGRAMMING 15 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
#16) Shell script to calculate employee salary
print enter the basic salaryread b(( da=$b*0.5 ))(( ta=$b*0.6 ))(( hra=$b*0.8 ))(( it=$b*0.4 ))(( grosssal=da+hra+ta+$b ))(( netsal=grosssal-it ))print gross salary is $netsal
output:
[root@localhost ~]# ksh 16enter the basic salary0700gross salary is 2500
UNIX PROGRAMMING 16 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
#17) Shell script to trap signals
trap 'ls;who' 2while truedo
print CTRL+C to see listing of current directoryprint and the users logged in and finally terminates the programprint
done
UNIX PROGRAMMING 17 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
#18) Shell script accepts two directory names as arguments #and deletes those files in the second directory which are #have names identical to the ones in the first directory
if (( $# == 2 )) thendirecto=$1directt=$2
elseprint enter directory1read directoprint enter directory2read directt
fifor fileinDO in $(ls $directo)do
for fileinDT in $(ls $directt)do
if [[ $fileinDO == $fileinDT ]] thenrm ./$directt/$fileinDT
fidone
done
UNIX PROGRAMMING 18 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
#19) Shell script to display the last ‘n’ line of every #file specified as a cnd line argument,preceded by the #name of the file
nol=$1shiftfor i in $*do
print '<==' $i '==>'tail --lines=$nol $i
done
UNIX PROGRAMMING 19 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
#20) Shell script to find total number of files in #directories and subdirectories"shellprogramming.txt"
# process list given to grep finds if process exists and #sends it # to cut command to retrieve process id
for i in $(ps -e|grep $processname|cut -f2 -d\ )do kill -9 $idone
UNIX PROGRAMMING 21 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
ASSIGNMENT-2
AWK PROGRAMMING
1.(a) Write a script that prints all input lines.
# Write a script that prints all input lines.
BEGIN {print"\t**Program to display all input lines**"i=0
}{
while(i<FNR){
print $0i++
}}END { print"Number of records " i}
(b) Write an awk command that prints the total number of fields in the file?
[mca1113@localhost Desktop]$ vi marks.dat
mca1101 50 60 40 80 90
mca1102 50 55 99 42 43
mca1103 43 53 55 29 75
mca1104 45 85 64 25 48
mca1105 46 52 17 39 52
mca1106 64 89 75 46 24
mca1107 87 64 28 49 33
mca1108 64 87 15 96 44
mca1109 80 90 87 64 37
UNIX PROGRAMMING 22 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
[mca1113@localhost Desktop]$ vi 1_b.awk
#write an awk script that prints the total number of fields in the file?
#Begin Block BEGIN{ count1=0
i=0count=0
}#Processing Block{ while(i<NF){ count++ i++ } print "Number of Fields in " count1+1 " record are " count count1++}#END BlockEND{ print "Number of records in file = " count1}
}
UNIX PROGRAMMING 23 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
2.(a) Write a script that prints the eighth line
# Write a script that prints the eighth line
BEGIN {print"\tProgram to display 8th line of file\n"i=0
}{
while(i<FNR){
if(i==8){
print"Eight Line is "$i"\n"}i++
}}END {
}
(b) Write an awk script to simulate following shell command CP file1 file2BEGIN{
while((getline x < ARGV[1])>0)print x > ARGV[2]
}
UNIX PROGRAMMING 24 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
3. Create an inventory file for the following data( do not include the column heads, only the data) call it as ch12s3f1Partno Price Quantityonhand Reorderpoint minimumorder
0123 1.23 23 20 200234 2.34 34 50 253456 34.56 56 50 104567 45.67 7 10 55678 6.78 75 75 25 (a) Create a script to prepare an inventory report. The report is to contain the partno, price, Quantity on hand, reorder point, minimum order and order amount. (b)The order amount calculated when the quantity on hand falls below the reorder point (c) Also provide a report heading such as “Inventory Report”, heading for each column and “End of report” message at the end of report. (d) Print the report
BEGIN {print"\t\tInventory Report\n"print"Partno Price Qtyonhand Reorder minorder Orderamount\n"i=0
}{
while(i<FNR)
UNIX PROGRAMMING 25 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
{if($2<$3)
amt=$1*$2print $0"\t"amt
i++}
}END {
print"\t\t End of Report"}
Report
BEGIN {print"\t\t*Inventory Report*\n"print"Partno Price Qtyonhand Reorder minorder Orderamount\n"i=0
}{
while(i<FNR){
amt=$1*$5print $0"\t"amti++
}}END {
print"amount "amt}
UNIX PROGRAMMING 26 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
4. Create a script that sends the contents of message file to everybody who has logged inPreparation: Create a file with a short friendly message and mention that this is a test message that should be discarded by the receiver.Script:Script name: message.scrArguments: one argument, a message fileValidation: (i)Ensure that exactly one argument is entered(ii)Ensure that argument is readable filenameBody Section: Create script that uses awk to create a temporary file containing the usernames of those Users who are logged into the system at this moment. Then send the message contained in the first argument to every logged –in user. Note that a user who has logged in more than once should receive only one messageTesting the Script:1. Test the script with no arguments2. Test the script with two arguments3. Test the script with one argument that is not readable file.4. Test the script with one valid argument You should include yourself in the recipient list. Check to see if you have received the message.
print x> system("write mca1104 print x")print x> system ("Hello")
}}
UNIX PROGRAMMING 27 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
ASSIGNMENT-3
PERL PROGRAMMING
1. Write a Perl program that takes a,b,c as input and calculates the value of the expression 10ab-((c-1)/17.44).
#Calculate 10ab-((c-1)/17.44).
print "Enter the value of a ";$a=<STDIN>;
print "Enter the value of b "; $b=<STDIN>;print "Enter the value of c "; $c=<STDIN>;
$res=10*$a*$b-(($c-1)/17.44);print "The result is $res";
output:[root@localhost Ass3]# vi 1.pl[root@localhost Ass3]# perl 1.plenter a value:1enter b value:2enter c value:3the result is: 19.8853211009174
UNIX PROGRAMMING 28 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
2. Write a Perl Program that takes three numbers as input and finds the second largest among them.
system("clear");print "\t\tFind the second largest number among the three numbers \n";print "Enter the first number ";
$a=<stdin>;print "Enter the second number "; $b=<stdin>;print "Enter the third number "; $c=<stdin>;
if($a>$b){if($a>$c){
if($b>$c){print"Second Largest number is $b";
}else{
print"Second Largest number is $c";}
}else{
print"Second Largest number is $a";}
}else{
if($b>$c) {if($a>$c) {
print"Second Largest number is $a";}else {
print"Second Largest number is $c";}
}else{
print"Second Largest number is $b";}
}output:[root@localhost Ass3]# vi 2.pl[root@localhost Ass3]# perl 2.plenter first no:10enter second no:20enter third no:30
The second largest is : 20
UNIX PROGRAMMING 29 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
3. Write a Perl Program to accept names in array and output the names in alphabetical order. Input: Three names, on separate lines from the keyboard. Output: Three Input names in alphabetical order.
@names;print "enter 3 names\n"; for($i=0;$i<3;$i++) { $names[$i]=<STDIN>; } print "the names are: @names\n"; @sortedlist=sort @names; print "the sorted list is: @sortedlist\n";output:[root@localhost Ass3]# perl 3.plenter 3 nameshabeebsirajimtiazthe names are: habeebsirajimtiazthe sorted list is: habeeb imtiaz siraj
UNIX PROGRAMMING 30 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
4. Write a Perl Program that contains a function that takes an array of numbers as parameters.Parameter: An array of numbersReturn value: The average and median of the parameter array.
sub func_average{my @new_arr=@_;foreach $i(@new_arr){
5. Write a Perl Program that demonstrates string functions.
print "enter two strings\n"; $str1=<STDIN>; $str=<STDIN>; $res=chomp($str,$str1);print"no.of lines are: $res\n"; $len=length($str);print"lengthof the string is: $len\n"; $upp=uc($str);print"upper case letters are: $upp\n"; $low=lc($str);print"lower case letters are: $low\n"; $name="habeeb"; $fullname="mk ".$name;print"concatenation of two string is: $fullname\n"; $j=join($str1, $str, 33);print"joining of two strings with number is: $j\n";
output:[root@localhost habib perl progs]# vi 6.pl[root@localhost habib perl progs]# perl 6.plenter two stringsmk habeebno.of lines are: 2lengthof the string is: 6upper case letters are: HABEEBlower case letters are: habeebconcatenation of two string is: mk habeebjoining of two strings with number is: habeebmk33
UNIX PROGRAMMING 32 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
6. Write a Perl Program that demonstrates the pattern matching capabilities.
print"enter a string\n"; $str=<STDIN>;print"1) It is a dot pattern match:\n"; if($str=~/h.beeb/){ print"\t its got to be habeeb\n"; }else{ print"\tbad luck\n"; }print"2) It is [aei] pattern match:\n"; if($str=~/h[aei]beeb/){
print"\t its got to be habeeb\n";
}else{ print"\tbad luck\n"; }print"3) It is [^aei] pattern match:\n"; if($str=~/h[^aei]beeb/){
print"\t its got to be habeeb\n";
}else{ print"\tbad luck\n"; }
print"4) It is beginning of shell pattern match:\n"; if($str=~/^habeeb/){
print"\t its got to be habeeb\n";
}else{ print"\tbad luck\n"; }
print"5) It is end of string pattern match:\n";
if($str=~/habeeb$/){
print"\t its got to be habeeb\n";
}else{ print"\tbad luck\n"; }
UNIX PROGRAMMING 33 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
output:
[root@localhost habib perl progs]# vi 9.pl[root@localhost habib perl progs]# perl 9.plenter a stringhabeeb1) It is a dot pattern match: its got to be habeeb2) It is [aei] pattern match: its got to be habeeb3) It is [^aei] pattern match: bad luck4) It is beginning of shell pattern match: It’s got to be habeeb5) It is end of string pattern match: It’s got to be habeeb
UNIX PROGRAMMING 34 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
7. Write a Perl program that takes as Input: A file that contains English words, where each word is separated from next word on a line by one space, specified on the command line.Output: A table, in which the first column has the unique words. From the input file and second column has the no. of times the word appeared in the file; no word can appear twice in the table.Method: Your program must use two arrays to store the table, one for the words and for the frequency values.
while (<>){#>>> Split the line into words@line_words = split /[ \.,;:!\?]\s*/;#>>> Loop to count the words (either increment or initialize to 1)foreach $word (@line_words){if (exists $freq{$word}){$freq{$word}++;}else{$freq{$word} = 1;}}}print "\n Word \t\t Frequency \n\n";foreach $word (sort keys %freq){print " $word \t\t $freq{$word} \n";}
UNIX PROGRAMMING 35 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
8. Write a Perl program that takes as Input: A file of lines of employee data where each line has name: age: department code: salaryOutput: 1. The names of all Employees whose names end with “son”2. Percentage of employees under 40 years old.3. Average salary of employees under 40 years old4. An alphabetical list of employees who are under 40 years old and who have salaries more than 40,000
open(EMPLOYEES, "employees.txt") || die "Can't open employees $!";print "Names that end in 'son'\n\n";# Loop to read and process the employee datawhile (<EMPLOYEES>){# Increment the number of employees and chop off the newline$total_employees++;chomp;# Split the input line into its four parts($name, $age, $dept, $salary) = split(/:/);# If the name ends in 'son', print the nameif ($name =~ /son$/){print "$name \n";}# If the employee is under 40, count him or her and add his or her# salary to the sum of such salariesif ($age < 40){$under_40++;$salary_sum += $salary;# If the salary was over 40,000, add the person and his or her# salary to the hash of such peopleif ($salary > 40000){$sublist{$name} = $salary;}}}# If there was at least one employee, continueif ($total_employees > 0){# If there was at least one under 40, continueif ($under_40 > 0){$percent = 100 * $under_40 / $total_employees;print "\nPercent of employees under 40 is: $percent \n";$avg = $salary_sum / $under_40;print "Average salary of employees under 40 is: $avg \n";if (keys(%sublist)){print "Sorted list of employees under 40"," with salaries > \$40,000 \n";
UNIX PROGRAMMING 36 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
@sorted_names = sort (keys(%sublist));print "\nName \t\t Salary\n";foreach $name (@sorted_names){print "$name \t \$$sublist{$name} \n";}}Else{print "There were no employees under 40 whoearned";print "over $40,000 \n";} #** of if (keys(%sublist))}else{print "There were no employees under 40 \n";} #** of if ($under_40 > 0)}else{print "There were no employees\n";} #** of if ($total_employees > 0)
UNIX PROGRAMMING 37 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
9. Write a Perl program that takes as Input: A file of text in which all words are separated by white space or punctuation like comma, a semicolon, a question mark, a period, or a colon. The input file is specified on command line. Output: A list of all unique words in the file in alphabetical order.
#Program to copy the content of a file in an Array and Display it in alphabetical Order@arr;open(INDAT,"<trail");while($a= <INDAT>){
@arr1=split(" ",$a);push(@arr,@arr1);
}@arr= sort(@arr);foreach $i(@arr){
print "\n\t$i";}
Text file
Hello WorldThis is Hello
a
UNIX PROGRAMMING 38 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
ASSIGNMENT - IV
Inter-Process Communication
1. Setup a two-way pipe between parent and child processes in a C program. i.e., both can send and receive messages.
#include"unistd.h"#include"stdio.h"
int main(){
char str[20], str1[20], str2[20];
int arr[2],arr1[2], pid;
pipe(arr);
pipe(arr1);
pid=fork();
if(pid==0){
printf("\n CHILD: Enter a message \n ");
scanf("%str", str);
write(arr[1], str,sizeof(str));
read(arr1[0], str2, sizeof(str2));
printf("\nCHILD\n Message read from parent : %s \n",str2);
}
else{
read(arr[0], str1, 20);printf("\nPARENT:\n Message from the child is %s\n", str1);printf("\nPARENT: Enter a message :\n");scanf("%s", str2);write(arr1[1],str2, sizeof(str2));
}}
UNIX PROGRAMMING 39 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
2. Write 2 programs that will both send and messages and construct the following dialog between them
(Process 1) Sends the message "Are you hearing me?"
(Process 2) Receives the message and replies "Loud and Clear".
(Process 1) Receives the reply and then says "I can hear you too".
//Program to send msg from process1.msg"Are you hearng me"#include<stdio.h>#include<stdlib.h>#include<sys/ipc.h>#include<string.h>
main(){
int pid,p1[2],p2[2],length;char str1[]="Are you hearing me?";char str2[]="loud and clear";char str3[]="yes i can here u to";
pipe(p1);pipe(p2);
pid=fork();
if(pid==0){
close(p1[0]);close(p2[1]);
printf("\n Process-1(cp) sends mesg : %s",str1);
write(p1[1],str1,sizeof(str1));// str2 [50] ="Loud and clear";
struct sockaddr_in servaddr,cliaddr;int sockfd,newsockfd,port,len,retval,client;char serv[50];printf("ENTER PORT NUMBER");scanf("%d",&port);printf("\nENTER IP ADDRESS");scanf("%s",serv);servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd==-1)perror("UNABLE TO SOCKET\n");retval=bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));if(retval==-1)perror("UNABLE TO BIND\n");retval=listen(sockfd,2);if(retval==-1)perror("UNABLE TO LISTEN\n");printf("STARTED CONNECTION....\n");while(1){
len=sizeof(cliaddr);newsockfd=accept(sockfd,(struct sockaddr *)&cliaddr,&len);if(newsockfd==-1){ perror("UNABLE TO CONNECT\n"); }client=ntohs(cliaddr.sin_port);printf("\nREADING FROM CLIENT AT PORT : %d",client);server_service(newsockfd);printf("\nSERVICED CLIENT AT PORT : %d\n",client);shutdown(newsockfd,2);
{if(read(newsockfd,str,sizeof(str))==-1)perror("UNABLE TO READ FROMCLIENT");if(write(newsockfd,str,sizeof(str))==-1)perror("ERROR WHILE WRITING");if(strcmp(str,"BYE")==0){
struct sockaddr_in servaddr;int sockfd,newsockfd,port;char serv[32];printf("ENTER PORT NUMBER : ");scanf("%d",&port);//printf("\nENTER IP ADDRESS : ");//scanf("%s",serv);strcpy(serv,"127.0.0.1");servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
{printf("\nENTER MESSAGE OR \"BYE\" TO EXIT : ");scanf("%s",msg);if(write(sockfd,msg,sizeof(msg))==-1)perror("UNABLE TO WRITE");if(read(sockfd,str,sizeof(str))==-1)perror("UNABLE TO READ");if(strcmp(str,"BYE")==0){
return;}else{
printf("%s\n",str);}
}}
OUTPUT:
SERVER:
[mca1002@localhost]~/UNIX/Sockets/EchoServer% cc CO_IT_server.c [mca1002@localhost]~/UNIX/Sockets/EchoServer% ./a.out ENTER PORT NUMBER5678ENTER IP ADDRESS127.0.0.1
STARTED CONNECTION....
READING FROM CLIENT AT PORT : 41208SERVICED CLIENT AT PORT : 41208
READING FROM CLIENT AT PORT : 41209SERVICED CLIENT AT PORT : 41209
^C
CLIENT 1:
[mca1002@localhost]~/UNIX/Sockets/EchoServer% cc CO_client.c [mca1002@localhost]~/UNIX/Sockets/EchoServer% ./a.out ENTER PORT NUMBER : 5678
ENTER MESSAGE OR "BYE" TO EXIT : hellohello
ENTER MESSAGE OR "BYE" TO EXIT : howhow
ENTER MESSAGE OR "BYE" TO EXIT : areare
ENTER MESSAGE OR "BYE" TO EXIT : you
UNIX PROGRAMMING 44 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
youENTER MESSAGE OR "BYE" TO EXIT : byebye
ENTER MESSAGE OR "BYE" TO EXIT : BYE[mca1002@localhost]~/UNIX/Sockets/EchoServer%
CLIENT 2:
[mca1002@localhost]~/UNIX/Sockets/EchoServer% cc CO_client.c [mca1002@localhost]~/UNIX/Sockets/EchoServer% ./a.out ENTER PORT NUMBER : 5678
ENTER MESSAGE OR "BYE" TO EXIT : hellohello
ENTER MESSAGE OR "BYE" TO EXIT : HOW HOW
ENTER MESSAGE OR "BYE" TO EXIT : AREARE
ENTER MESSAGE OR "BYE" TO EXIT : YOUYOU
ENTER MESSAGE OR "BYE" TO EXIT : BYE
[mca1002@localhost]~/UNIX/Sockets/EchoServer%
UNIX PROGRAMMING 45 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
4. Write 2 programs that will communicate both ways (i.e each process can read and write) when run concurrently via semaphores.
down(resource);//wait(wrt)printf("\nWRITER IS ACTIVE\n");fp=fopen("file","w");if(fp==NULL){
perror("CANNOT OPEN FILE");exit(0);
}printf("ENTER SOME TEXT TO BE WRITTEN TO THE FILE\n");gets(text);fputs(text,fp);fclose(fp);printf("WRITER FINISHED WRITING\n");if(strcmp(text,"BYE")==0){
[mca1002@localhost]~/UNIX/Semaphores% cc Writer.c /tmp/ccMiIL7T.o: In function `writer':Writer.c:(.text+0x236): warning: the `gets' function is dangerous and should not be used.
[mca1002@localhost]~/UNIX/Semaphores% ./a.out
WRITER IS ACTIVEENTER SOME TEXT TO BE WRITTEN TO THE FILEhello to allWRITER FINISHED WRITING
WRITER IS ACTIVEENTER SOME TEXT TO BE WRITTEN TO THE FILEsocket is goodWRITER FINISHED WRITING
WRITER IS ACTIVEENTER SOME TEXT TO BE WRITTEN TO THE FILEgoing to close nowWRITER FINISHED WRITING
UNIX PROGRAMMING 51 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
WRITER IS ACTIVEENTER SOME TEXT TO BE WRITTEN TO THE FILEbyeWRITER FINISHED WRITING
WRITER IS ACTIVEENTER SOME TEXT TO BE WRITTEN TO THE FILEBYEWRITER FINISHED WRITING
WRITER ENDING NOW
READER 1:
[mca1002@localhost]~/UNIX/Semaphores% cc Reader.c [mca1002@localhost]~/UNIX/Semaphores% ./a.out
READER IS ACTIVEhello to allREADER FINISHED READING
READER IS ACTIVEsocket is goodREADER FINISHED READING
READER IS ACTIVEgoing to close nowREADER FINISHED READING
READER IS ACTIVEbyeREADER FINISHED READING
READER IS ACTIVEBYEREADER FINISHED READING
READING ENDING NOW
READER 2:
[mca1002@localhost]~/UNIX/Semaphores% cc Reader.c [mca1002@localhost]~/UNIX/Semaphores% ./a.out
READER IS ACTIVEhello to allREADER FINISHED READING
READER IS ACTIVEsocket is good
UNIX PROGRAMMING 52 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
READER FINISHED READING
READER IS ACTIVEgoing to close nowREADER FINISHED READING
READER IS ACTIVEbyeREADER FINISHED READING
READER IS ACTIVEBYEREADER FINISHED READING
READING ENDING NOW
READER 3 JOINED LATER:
[mca1002@localhost]~/UNIX/Semaphores% cc Reader.c [mca1002@localhost]~/UNIX/Semaphores% ./a.out
READER IS ACTIVEsocket is goodREADER FINISHED READING
READER IS ACTIVEgoing to close nowREADER FINISHED READING
READER IS ACTIVEbyeREADER FINISHED READING
READER IS ACTIVEBYEREADER FINISHED READING
READING ENDING NOW
UNIX PROGRAMMING 53 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
5. write the programs shmget.c, shmctl.c and shmop.c and then
investigate and understand fully the operations of the flags (access, creation etc. permissions) you can set interactively in the programs.
Use the prgrams to:
o Exchange data between two processe running as shmop.c. o Inquire about the state of shared memory with shmctl.c. o Use semctl.c to lock a shared memory segment. o Use semctl.c to delete a shared memory segment.
#include "stdio.h"
#include "string.h"
#include "sys/ipc.h"
#include "sys/types.h"
#include "sys/shm.h"
int main()
{
int shmid;
char *msg, str[20];
shmid = shmget((key_t)0x10,20,IPC_CREAT|0666);
msg=shmat(shmid,0,0);
printf("\n The message read from the shared memory is %s \n", msg);
}
#include "stdio.h"
#include "string.h"
#include "sys/ipc.h"
#include "sys/types.h"
#include "sys/shm.h"
UNIX PROGRAMMING 54 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
int main()
{
int shmid;
char *msg, str[20];
shmid = shmget((key_t)0x10,20,IPC_CREAT|0666);
msg=shmat(shmid,0,0);
if(shmid>0)
{
printf("\n The shared memory segment has been created \n");
printf("\n Enter a string :\t");
scanf("%s",str);
strcpy(msg,str);
printf("\n String is stored in the shared memory\n ");
}
}
UNIX PROGRAMMING 55 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
6. Write a program to demonstrate signal communication.
#include<stdio.h>#include<signal.h>
void abc(){
printf("Signal handler function\n");}
main(){
int pid;
pid=fork();if(pid==0){
signal(SIGQUIT,abc);printf("\nWaiting for the signal from parent");fflush(stdout);sleep(5);
}else{
printf("\nEnter the ctrl+\\ Key combination\n");fflush(stdout);sleep(5);kill(getpid(), SIGQUIT);
struct sockaddr_in servaddr;int sockfd,newsockfd,port;char serv[32],msg[20],str[20];printf("ENTER PORT NUMBER : ");scanf("%d",&port);printf("\nENTER IP ADDRESS : ");scanf("%s",serv);servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ perror("UNABLE TO SOCKET");exit(0); }if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))!=0){ perror("UNABLE TO CONNECT");exit(0);}printf("\nENTER MESSAGE : ");scanf("%s",msg);if(write(sockfd,msg,sizeof(msg))==-1)perror("UNABLE TO WRITE");if(read(sockfd,str,sizeof(str))==-1)perror("UNABLE TO READ");printf("\n%s\n",str);shutdown(sockfd,2);
}
OUTPUT:
[mca1002@localhost]~/UNIX/Sockets/EchoServer% cc co_client_ori.c [mca1002@localhost]~/UNIX/Sockets/EchoServer% ./a.out ENTER PORT NUMBER : 7ENTER IP ADDRESS : 127.0.0.1ENTER MESSAGE : hellohello
UNIX PROGRAMMING 58 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
9. Write client/server programs using connection less service. Implement server as Date Timeserver.
char command[6];struct sockaddr_in servaddr;int sockfd,port,len;char serv[20],msg[40];printf("\nENTER PORT NUMBER : ");scanf("%d",&port);printf("\nENTER IP ADDRESS : ");scanf("%s",serv);servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1)perror("UNABLE TO SOCKET");strcpy(command,"DATE");if(sendto(sockfd,command,sizeof(command),0,(struct sockaddr*)&servaddr,sizeof(servaddr))==-1)
perror("CLIENT COULD NOT SEND\n");len=sizeof(servaddr);if(recvfrom(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&servaddr,&len)==-1)
perror("CLIENT COULD NOT RECEIVE\n");printf("\n%s\n",msg);shutdown(sockfd,2);}
OUTPUT:
[root@localhost DayTime]# cc CL_client.c [root@localhost DayTime]# ./a.outENTER PORT NUMBER : 13ENTER IP ADDRESS : 127.0.0.1
Sun Jun 26 15:03:04 2011
UNIX PROGRAMMING 59 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
10. Write client/server programs using connection oriented service. Implement server as it gives result of command which is requested by client. The output has to be displayed in client.
int pid,i;char ch,filename[20],command[30];struct sockaddr_in servaddr,cliaddr;int sockfd,newsockfd,port,len,retval,client;char serv[50],str[2048];printf("ENTER PORT NUMBER : ");scanf("%d",&port);printf("\nENTER IP ADDRESS : ");scanf("%s",serv);servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);sockfd=socket(AF_INET,SOCK_STREAM,0);if(sockfd==-1)perror("UNABLE TO SOCKET\n");retval=bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));if(retval==-1)perror("UNABLE TO BIND\n");retval=listen(sockfd,3);if(retval==-1)perror("UNABLE TO LISTEN\n");while(1){
len=sizeof(cliaddr);newsockfd=accept(sockfd,(struct sockaddr *)&cliaddr,&len);if(newsockfd==-1)perror("UNABLE TO ACCEPT\n");client=ntohs(cliaddr.sin_port);printf("READING FROM CLIENT : %d\n",client);pid=fork();if(pid==0){
int fp;FILE *fc;
if(read(newsockfd,filename,sizeof(filename))==-1)perror("UNABLE TO READ SERVER");
int pid;char ch,filename[20],command[30];struct sockaddr_in servaddr;int sockfd,newsockfd,port,len;char serv[20],str[20],msg[2048];printf("\nENTER PORT NUMBER : ");scanf("%d",&port);printf("\nENTER IP ADDRESS : ");scanf("%s",serv);servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)perror("UNABLE TO SOCKET");if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))==-1)
perror("UNABLE TO CONNECT");printf("\nENTER FILENAME : ");scanf("%s",filename);if(write(sockfd,filename,sizeof(filename))==-1)perror("UNABLE TO WRITE");if(read(sockfd,msg,sizeof(msg))==-1)perror("UNABLE TO READ");printf("\n%s\n",msg);shutdown(sockfd,2);
}
OUTPUT:
SERVER:
[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% cc CO_IT_server.c[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% ./a.out ENTER PORT NUMBER : 7000ENTER IP ADDRESS : 127.0.0.1
READING FROM CLIENT : 44739SUM IS 15 SERVICED CLIENT : 44739
READING FROM CLIENT : 44742SUM IS 15 SERVICED CLIENT : 44742
^C
UNIX PROGRAMMING 62 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
CLIENT 1:
[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% cc CO_client.c[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% ./a.out ENTER PORT NUMBER : 7000ENTER IP ADDRESS : 127.0.0.1
ENTER FILENAME : sum.c
SUM IS 15CLIENT 2:
[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% cc CO_client.c[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% ./a.outENTER PORT NUMBER : 7000ENTER IP ADDRESS : 127.0.0.1
ENTER FILENAME : sum.c
SUM IS 15
UNIX PROGRAMMING 63 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
12. Write client/server programs using connection oriented service. Implement server as it validates username/password given by client and send back result to client.
int pid,p1[2],p2[2],found=0;char name[20],passwd[20],nametemp[20],passwdtemp[20],status[20];FILE *fp;pipe(p1);pipe(p2);pid=fork();if(pid==-1){ perror("FAILURE"); }else if(pid!=0){
close(p1[0]);close(p2[1]);printf("ENTER USER NAME : \n");gets(name);printf("ENTER PASSWORD : \n");gets(passwd);write(p1[1],name,sizeof(name));write(p1[1],passwd,sizeof(passwd));read(p2[0],status,sizeof(status));printf("%s",status);
[mca1002@localhost]~/UNIX/Pipes% cc q7.c /tmp/cccnZrKc.o: In function `main':q7.c:(.text+0x90): warning: the `gets' function is dangerous and should not be used.
[mca1002@localhost]~/UNIX/Pipes% ./a.outENTER USER NAME : mca1002ENTER PASSWORD : mca1002ACCESS GRANTED
UNIX PROGRAMMING 65 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
13 .Write client/server programs using connection oriented service. Implement server as it sends contents of file which is requested by client. The content has to be displayed in client.
#include<stdio.h>#include<unistd.h>main(){
int pid,p1[2],p2[2];char source[20],dest[20],ch;FILE *fpSource,*fpDest;
close(p2[0]);close(p1[1]);read(p1[0],source,20);printf("ENTER DESTINATION FILE NAME FOR COPYING : ");gets(dest);fpSource=fopen(source,"r");fpDest=fopen(dest,"w");if(fpSource==NULL||fpDest==NULL){
printf("CANNOT OPEN FILES\n");write(p2[1],"FAILURE",20);
[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/Readv_Writev% cc readv_writev.c[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/Readv_Writev% ./a.out ENTER PORT NUMBER : 8900
CLIENT:
[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/Readv_Writev% cc client.c[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/Readv_Writev% ./a.out ENTER PORT NUMBER : 8900hellotoyou
UNIX PROGRAMMING 70 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
14 b. Demonstrate the getpeername, getsockname socket system calls.
printf ("\n Enter a string to send : ");scanf("%s",str1);
write(sockfd,str1,20);
read(sockfd,str2,20);
printf("\n Received string is : %s",str2);}OUTPUT:
SERVER:
[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% cc getpeersock.c [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% ./a.outENTER PORT NUMBER : 5678PEER PORT : 53928SELF PORT : 5678
CLIENT:
[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% cc client.c [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% ./a.outENTER PORT NUMBER : 5678PEER PORT : 5678SELF PORT : 53928
UNIX PROGRAMMING 73 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
14 c. Demonstrate the getsockopt, setsockopt socket system calls.
int filedesc[2];char str[20],msg[10]="HELLO";socketpair(AF_UNIX,SOCK_STREAM,0,filedesc);shutdown(filedesc[0],0);shutdown(filedesc[1],1);write(filedesc[0],msg,sizeof(msg));read(filedesc[1],str,sizeof(str));printf("STRING : %s\n",str);
}
OUTPUT:
[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/sockpairShutdown% cc socketpairShutdown.c [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/sockpairShutdown% ./a.out
STRING : HELLO
UNIX PROGRAMMING 75 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
14 e. Demonstrate the rresvport socket system calls
The rresvport() function is used to obtain a socket with a privileged address bound to it. This socket is suitable for use by rcmd() and several other functions. Privileged Internet ports are those in the range 0 to 1023. Only the superuser is allowed to bind an address of this sort to a socket. */
#include<unistd.h>#include<stdio.h>
int main(){
int port_no,sockfd;
sockfd=rresvport(&port_no);
if (sockfd==-1)perror("Socket not created");
printf("\n The port no allocated by rresvport is : %d",port_no);}OUTPUT:
[root@localhost rresvport]# cc rresvport.c [root@localhost rresvport]# ./a.out
PORT BY rresvport : 3
UNIX PROGRAMMING 76 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
15. Write a program to demonstrate asynchronous I/O.
[mca1002@localhost]~/UNIX/Sockets/Asynchronous% cc AsyncEchoServer_server.c [mca1002@localhost]~/UNIX/Sockets/Asynchronous% ./a.outENTER PORT NUMBER8900STARTED CONNECTION....
SERVER DOING ITS OWN WORK : 0SERVER DOING ITS OWN WORK : 1SERVER DOING ITS OWN WORK : 2
READING FROM CLIENT AT PORT : 65535SERVICED CLIENT AT PORT : 65535
SERVER DOING ITS OWN WORK : 3
UNIX PROGRAMMING 79 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
CLIENT:
[mca1002@localhost]~/UNIX/Sockets/Asynchronous% cc AsyncEchoServer_client.c [mca1002@localhost]~/UNIX/Sockets/Asynchronous% ./a.out ENTER PORT NUMBER : 8900ENTER MESSAGE : hellohello
UNIX PROGRAMMING 80 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
16. Write a program to implement the Internet Super server
struct sockaddr_in servaddr1,servaddr2,cliaddr;int sockfd[2],newsockfd,port1,port2,len,retval,client,i,pid;char serv[50];fd_set fs;printf("ENTER PORT NUMBER FOR ECHO : ");scanf("%d",&port1);printf("ENTER PORT NUMBER FOR DAYTIME : ");scanf("%d",&port2);strcpy(serv,"127.0.0.1");
if(sockfd[0]==-1||sockfd[1]==-1)perror("UNABLE TO SOCKET\n");retval=bind(sockfd[0],(struct sockaddr *)&servaddr1,sizeof(servaddr1));if(retval==-1)perror("UNABLE TO BIND\n");retval=bind(sockfd[1],(struct sockaddr *)&servaddr2,sizeof(servaddr2));if(retval==-1)perror("UNABLE TO BIND\n");
retval=listen(sockfd[0],2);if(retval==-1)perror("UNABLE TO LISTEN\n");
retval=listen(sockfd[1],2);if(retval==-1)perror("UNABLE TO LISTEN\n");printf("STARTED CONNECTION....\n");while(1){
struct sockaddr_in servaddr;int sockfd,newsockfd,port;char serv[32],msg[20],str[20];printf("ENTER PORT NUMBER : ");scanf("%d",&port);//printf("\nENTER IP ADDRESS : ");//scanf("%s",serv);strcpy(serv,"127.0.0.1");servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);
}printf("\nENTER MESSAGE : ");scanf("%s",msg);if(write(sockfd,msg,sizeof(msg))==-1)perror("UNABLE TO WRITE");if(read(sockfd,str,sizeof(str))==-1)perror("UNABLE TO READ");printf("\n%s\n",str);shutdown(sockfd,2);
int pid;char ch,filename[20],command[30];struct sockaddr_in servaddr;int sockfd,newsockfd,port,len;char serv[20],str[20],msg[35];printf("\nENTER PORT NUMBER : ");scanf("%d",&port);printf("\nENTER IP ADDRESS : ");scanf("%s",serv);servaddr.sin_family=AF_INET;servaddr.sin_port=htons(port);servaddr.sin_addr.s_addr=inet_addr(serv);if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)perror("UNABLE TO SOCKET");if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))==-1)
perror("UNABLE TO CONNECT");strcpy(command,"DATE");if(write(sockfd,command,sizeof(command))==-1)perror("UNABLE TO WRITE");if(read(sockfd,msg,sizeof(msg))==-1)perror("UNABLE TO READ");printf("\n%s\n",msg);shutdown(sockfd,2);
}
OUTPUT:
SERVER:
[mca1002@localhost]~/UNIX/Sockets/Internet% cc InternetSuperServer.c[mca1002@localhost]~/UNIX/Sockets/Internet% ./a.out
ENTER PORT NUMBER FOR ECHO : 5678
ENTER PORT NUMBER FOR DAYTIME : 6789
STARTED CONNECTION....
READING FROM CLIENT AT PORT : 48669SERVICED CLIENT AT PORT : 48669
READING FROM CLIENT AT PORT : 37457SERVICED CLIENT AT PORT : 37457
UNIX PROGRAMMING 84 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
^C
CLIENT 1 AT ECHO PORT:
[mca1002@localhost]~/UNIX/Sockets/Internet% cc ECHO_CO_client.c[mca1002@localhost]~/UNIX/Sockets/Internet% ./a.out
ENTER PORT NUMBER : 5678
ENTER MESSAGE : hello
hello
CLIENT 1 AT DAYTIME PORT:
[mca1002@localhost]~/UNIX/Sockets/Internet% cc DATE_CO_client.c[mca1002@localhost]~/UNIX/Sockets/Internet% ./a.out
ENTER PORT NUMBER : 6789ENTER IP ADDRESS : 127.0.0.1
Wed Jun 22 06:52:13
UNIX PROGRAMMING 85 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
ASSIGNMENT – V
PHP SERVER SCRIPT
[root@localhost PHP]# cat Hello.php 1.Write a PHP script to display Hello World Message
<HTML><HEAD>
<TITLE>WELCOME MESSAGE
</TITLE></HEAD><BODY>
<?phpecho 'hello';print '<BR>hello<BR />';
?></BODY>
</HTML>
UNIX PROGRAMMING 86 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
2.Write a PHP script to demonstrate string functions<HTML>
<HEAD><TITLE>
DEMO STRING FUNCTIONS</TITLE>
</HEAD><BODY>
<?php$str='hello';$len=strlen($str);print "<BR>LENGTH OF HELLO : ".$len."<BR />";$str2='HELLO';if(strcmp($str,$str2)==0)
8. Write a php script which has a function that takes File variable of file as argument and returns the Word which appears most often.
<HTML><HEAD>
<TITLE>FILE ARGUMENT IN FUNCTION RETURN COUNT OF WORDS
AND RETURN WORD WITH MAXIMUM COUNT</TITLE><?php
function wordCount($fp,$name){
$freq=array();$arrayfinal=array();$file_stringf=fread($fp,filesize($name));print "ORIGINAL TEXT : $file_stringf<BR>";$file_string=preg_split("/[\s\n\.,;:!\?*]/",$file_stringf);foreach ($file_string as $word){
$keys=array_keys($freq);if(in_array($word,$keys))
$freq[$word]++;else
$freq[$word]=1;}$max=0;foreach($freq as $keys=>$values){
if($values>=$max){ $max=$values; }
}foreach($freq as $keys=>$values){
if($values==$max){ $arrayfinal[$keys]=$values; }
}
return $arrayfinal;}
?></HEAD>
<BODY><?php
$filename="text";$fp=fopen($filename,'r');$arrfin=wordCount($fp,$filename);foreach($arrfin as $keys=>$values){
print "$keys => $values<BR>";}
?>
UNIX PROGRAMMING 94 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
</BODY></HTML>
UNIX PROGRAMMING 95 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
9. Write a php script to demonstrate call by reference And form submitting values to itself
10. PHP SCRIPT TO DEMONSTRATE SCOPE AND LIFETIMEOF VARIABLES.<HTML><HEAD>
<TITLE>SCOPE AND LIFETIME OF VARIABLES</TITLE></HEAD><BODY>
<?php$number=10;print "<H3>";print "<BR>LOCAL NUMBER DEMO";print "<BR>number outside function : $number";function AddNumber(){
$number;print "<BR>number inside function : $number";$number=30;print "<BR>number now assigned value : $number";$number+=10;print "<BR>number after incrementing by 10: $number";
}AddNumber();print "<BR>number after (outside) function call: $number";print "<BR><BR>";print "GLOBAL NUMBER DECLARATION DEMO";print "<BR>number outside function : $number";function addNum(){
global $number;print "<BR>number inside function : $number";$number=30;print "<BR>number now assigned value : $number";$number+=10;print "<BR>number after incrementing by 10: $number";
}addNum();print "<BR>number after (outside) function call: $number";print "<BR><BR>";print "LIFETIME DEMO";
}print "<BR>First function call";addNumLife();print "<BR>Second function call";addNumLife();print "<BR>Third function call";addNumLife();print "</H3>";
UNIX PROGRAMMING 98 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
?></BODY></HTML>
UNIX PROGRAMMING 99 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
11.WRITE A PHP SCRIPT TO DEMONSTRATE THE USE OF PREG_MATCH AND PREG_SPLIT FUNCTIONS.
12. Write the html code to accept employee information as followsI) text boxes to accept employee name, roll no, address and salaryII) a radio button to accept the type of employee
Write a php script that processes the employee information and generates the salary slip
print "<H2>";print("TOTAL SALARY IS $TOTAL");print "</H2>";
?></BODY>
</HTML>
UNIX PROGRAMMING 103 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
13. Write html code to create a feedback form to accept Details like name, father's name, address, gender, Occupation (as a drop down list).Store these details in a file by making use of a php a script.
<?php$fileop='/var/www/html/PHP/student.dat';//$fp=fopen($fileop,'r') or die('cannot open');$file_lines=file($fileop);foreach ($file_lines as $words){
print "<BR>record : ";$wordArray=preg_split("/:/",$words);foreach($wordArray as $printWord){
print "$printWord\t";}
}?>
</BODY></HTML>
UNIX PROGRAMMING 107 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
UNIX PROGRAMMING 108 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
14. Write a supermarket form with the following Capabilities :
(i) a text box to accept the customer name(ii) five text boxes to accept five different items and their
corresponding quantities.(iii) Three radio buttons to accept mode of payment.(iv) A text area to accept the address.
Write a php script to process the supermarket form And display the results in the form of a bill as a Table.store the details in a file for future reference.
print "<H4>MODE OF PAYMENT : $mode</H4>";print "<H4>TOTAL QUANTITY: $total_qty</H4>";print "<H4>TOTAL PRICE: $total_price</H4>";$file_var=fopen("superMarket.dat","a") or die("cannot open");fwrite($file_var,$name);fwrite($file_var,":");fwrite($file_var,$street);fwrite($file_var,":");fwrite($file_var,$citypin);fwrite($file_var,":");fwrite($file_var,$quan1);fwrite($file_var,":");fwrite($file_var,$price1);fwrite($file_var,":");fwrite($file_var,$quan2);fwrite($file_var,":");fwrite($file_var,$price2);fwrite($file_var,":");fwrite($file_var,$quan3);fwrite($file_var,":");fwrite($file_var,$price3);fwrite($file_var,":");fwrite($file_var,$quan4);fwrite($file_var,":");fwrite($file_var,$price4);fwrite($file_var,":");fwrite($file_var,$quan5);fwrite($file_var,":");fwrite($file_var,$price5);fwrite($file_var,":");fwrite($file_var,$item_cost1);fwrite($file_var,":");fwrite($file_var,$item_cost2);fwrite($file_var,":");fwrite($file_var,$item_cost3);fwrite($file_var,":");fwrite($file_var,$item_cost4);fwrite($file_var,":");fwrite($file_var,$item_cost5);fwrite($file_var,":");fwrite($file_var,$mode);fwrite($file_var,":");fwrite($file_var,$total_qty);fwrite($file_var,":");fwrite($file_var,$total_price);
UNIX PROGRAMMING 113 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
fwrite($file_var,"\n");fclose($file_var);?>
</CENTER><HR COLOR="LIGHTGREY" SIZE="3"><CENTER><H1>THANK YOU<BR>HAVE A NICE
DAY!!!</H1></CENTER></BODY></HTML>
[root@localhost PHP]# cat superMarketReader.php
<HTML><HEAD>
<TITLE>FEED BACK FORM
</TITLE></HEAD><BODY BGCOLOR="DARKGREY">
<?php$fileop='/var/www/html/PHP/superMarket.dat';//$fp=fopen($fileop,'r') or die('cannot open');$file_lines=file($fileop);foreach ($file_lines as $words){
print "<BR>record : ";$wordArray=preg_split("/:/",$words);foreach($wordArray as $printWord){
print "$printWord\t";}
}?>
</BODY></HTML>
UNIX PROGRAMMING 114 MCA IInd Year IInd Sem
MJCET 1604-10-862-007
15. Write a php script to demonstrate cookies.<HTML>