Sunteți pe pagina 1din 155

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

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

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)
rename .c .old *.c [root@localhost ~]# ls 1.c anaconda-ks.cfg Desktop install.log.syslog rename sum.c wcount add.c a.out install.log mca1107 scsrun.log tmp [root@localhost ~]#ksh rename output:

[root@localhost ~]# ls 1.old anaconda-ks.cfg Desktop install.log.syslog rename sum.old wcount add.old a.out install.log mca1107 scsrun.log tmp

UNIX PROGRAMMING

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

# 3) Shell script to concat the contents of two files into a destination file
[root@localhost ~]# vi file1 print this is the contents of the first file [root@localhost ~]# vi file2 print this is the content of the second file

cat file1 file2 >file3

output:

Print this is the contents of the first file print this is the content of the second file

UNIX PROGRAMMING

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

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 $0 print The process id is $$

output: The script name is 4 The process id is 3274

UNIX PROGRAMMING

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:year date +%T:%A:%d:%B:%y

output: [root@localhost ~]# ksh 5 date in the order:time :day of the week:day:month:year 12:46:17:Sunday:27:March:11

UNIX PROGRAMMING

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

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 >> temp done cat temp

output: [root@localhost ~]# ksh 6 file1 file3 temp print this is the contents of the first file print this is the contents of the first file print this is the content of the second file print this is the contents of the first file print this is the contents of the first file print this is the content of the second file

UNIX PROGRAMMING

10

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

11

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 fi done output: [root@localhost ~]# ksh 7 mca1107 file1 mca1107 is a directory file1 is a regular file

UNIX PROGRAMMING

12

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

# 8) Shell script to find the exit status of a command

print enter two numbers read num1 num2 if(( $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 8 enter two numbers 20 07 if condition is true exit status is 0

UNIX PROGRAMMING

13

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 exit do case $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 ;; UNIX PROGRAMMING 14 MCA IInd Year IInd Sem

MJCET esac done

1604-10-862-007

# 10) Shell script to make the calendar command interactive

print INTERACTIVE CALENDAR OPTIONS print 1 For current month print 2 For current year print 3 For three months print 4 For the year.x print 5 For the x month of x year print 6 To exit print Enter your choice. read ch case $ch in 1) print current month cal -1 ;; UNIX PROGRAMMING 15 MCA IInd Year IInd Sem

MJCET 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

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 UNIX PROGRAMMING 16 MCA IInd Year IInd Sem

MJCET read pattern for i in * do if [[ -f $i ]] then grep $pattern $i fi done output:

1604-10-862-007

[root@localhost ~]# ksh 11 enter the pattern you want to find in all the files of the directory copy select ch in copy remove rename link exit copy) print enter two file names. print copy completed..contents of file1 copied into file2 ;;

UNIX PROGRAMMING

17

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 name read file if [[ -x $file ]] then print this is exe file else print this is not exe file fi output: [root@localhost ~]# ksh 12 enter the file name a.out this is exe file

UNIX PROGRAMMING

18

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 file read file print "converting all lower to upper case letters" cat $file|tr a-z A-Z print "converting all upper to lower case letters" cat $file|tr A-Z a-z OUTPUT: [root@localhost ~]# ksh 13 enter file abc converting all lower to upper case letters THIS IS KORN SHELL THIS IS KORN SHELL converting all upper to lower case letters this is korn shell this is korn shell

UNIX PROGRAMMING

19

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 output: [root@localhost ~]# ksh 14 1 + 2 3 [root@localhost ~]# ksh 14 2 - 2 0 [root@localhost ~]# ksh 14 2 x 2 UNIX PROGRAMMING 20 MCA IInd Year IInd Sem

MJCET 4 [root@localhost ~]# ksh 14 2 / 2 1

1604-10-862-007

# 15) Shell script to find out whether a given year is #leap year or not

print enter the year read year if (( year%4 == 0 )) then print leap year else UNIX PROGRAMMING 21 MCA IInd Year IInd Sem

MJCET print not a leap year fi output: [root@localhost ~]# ksh 15 enter the year 1988 leap year

1604-10-862-007

UNIX PROGRAMMING

22

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

#16) Shell script to calculate employee salary

print enter the basic salary read 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 16 enter the basic salary 0700 gross salary is 2500

UNIX PROGRAMMING

23

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

#17) Shell script to trap signals


trap 'ls;who' 2 while true do print CTRL+C to see listing of current directory print and the users logged in and finally terminates the program print done

UNIX PROGRAMMING

24

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 )) then directo=$1 directt=$2 else print enter directory1 read directo print enter directory2 read directt fi for fileinDO in $(ls $directo) do for fileinDT in $(ls $directt) do if [[ $fileinDO == $fileinDT ]] then rm ./$directt/$fileinDT fi done done

UNIX PROGRAMMING

25

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=$1 shift for i in $* do print '<==' $i '==>' tail --lines=$nol $i done

UNIX PROGRAMMING

26

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"
if (( $# == 1 )) then direct=$1 else print enter directory UNIX PROGRAMMING 27 MCA IInd Year IInd Sem

MJCET read direct fi for files in $(ls $direct) do if [[ -d $direct/$files ]] then print $files $(ls $direct/$files|grep -c '^') files fi done print present directory $(ls $direct|grep -c '^') files

1604-10-862-007

UNIX PROGRAMMING

28

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

#21) Shell script to kill a process by name


Ps #accepting process name and printing its id print enter name of process read processname # 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 $i done

UNIX PROGRAMMING

29

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 $0 i++ } } END { print"Number of records " i }

UNIX PROGRAMMING

30

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

(b) Write an awk command that prints the total number of fields in the file? [mca1113@localhost Desktop]$ vi marks.dat mca1101 50 mca1102 50 mca1103 43 mca1104 45 mca1105 46 mca1106 64 mca1107 87 mca1108 64 mca1109 80 60 55 53 85 52 89 64 87 90 40 99 55 64 17 75 28 15 87 80 42 29 25 39 46 49 96 64 90 43 75 48 52 24 33 44 37

[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=0 count=0 } #Processing Block { while(i<NF){ count++ i++ } print "Number of Fields in " count1+1 " record are " count count1++ UNIX PROGRAMMING 31 MCA IInd Year IInd Sem

MJCET } #END Block END{ print "Number of records in file = " count1 }

1604-10-862-007

UNIX PROGRAMMING

32

MCA IInd Year IInd Sem

MJCET 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 file2 BEGIN{ while((getline x < ARGV[1])>0) print x > ARGV[2] }

1604-10-862-007

UNIX PROGRAMMING

33

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

34

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 ch12s3f1 Partno Price Quantityonhand Reorderpoint minimumorder 0123 1.23 23 20 20 0234 2.34 34 50 25 3456 34.56 56 50 10 4567 45.67 7 10 5 5678 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 Data file: [root@localhost awk]$ cat invntry.dat 100 10 100 250 130 101 30 100 50 40 102 99 50 20 10 Inventory Report BEGIN { print"\t\t*Inventory Report*\n" print"Partno Price Qtyonhand Reorder minorder Orderamount\n" i=0 } { while(i<FNR) { if($2<$3) amt=$1*$2 print $0"\t"amt i++ } } END { print"amount "amt } UNIX PROGRAMMING 35 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

(C) BEGIN { print"\t\tInventory Report\n" print"Partno Price Qtyonhand Reorder minorder Orderamount\n" i=0 } { while(i<FNR) { if($2<$3) amt=$1*$2 print $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*$5 print $0"\t"amt i++ } } END { print"amount "amt } UNIX PROGRAMMING 36 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

37

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 in Preparation: 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.scr Arguments: one argument, a message file Validation: (i)Ensure that exactly one argument is entered (ii)Ensure that argument is readable filename Body 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 message Testing the Script: 1. Test the script with no arguments 2. Test the script with two arguments 3. 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. BEGIN{ } #Processing Block { # system("write mca1111") while((getline x < ARGV[1])>0) { print x> system("wall x") } } BEGIN{ } #Processing Block { # system("write mca1111") while((getline x < ARGV[1])>0) { UNIX PROGRAMMING 38 MCA IInd Year IInd Sem

MJCET print x> system("write mca1104 print x") print x> system ("Hello") } }

1604-10-862-007

UNIX PROGRAMMING

39

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.pl enter a value:1 enter b value:2 enter c value:3 the result is: 19.8853211009174

UNIX PROGRAMMING

40

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"; UNIX PROGRAMMING 41 MCA IInd Year IInd Sem

MJCET } } else{ print"Second Largest number is $b"; } } output: [root@localhost Ass3]# vi 2.pl [root@localhost Ass3]# perl 2.pl enter first no:10 enter second no:20 enter third no:30 The second largest is : 20

1604-10-862-007

UNIX PROGRAMMING

42

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.pl enter 3 names habeeb siraj imtiaz the names are: habeeb siraj imtiaz the sorted list is: habeeb imtiaz siraj

UNIX PROGRAMMING

43

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

44

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 numbers Return value: The average and median of the parameter array. sub func_average{ my @new_arr=@_; foreach $i(@new_arr){ $sum+=$i; $count++; } $avg = $sum/$count; return $avg; } sub func_median{ my @arr1= @_; for($j=0;$j<$n-1;$j++){ for($k=$j+1;$k<$n;$k++){ if($arr1[$k]>$arr1[$j]){ $temp=$arr1[$k]; $arr1[$k]=$arr1[$j]; $arr1[$j]=$temp; } } } $med = ($arr1[0]+$arr1[$n-1])/2; return $med; } $sum=0; print "\n\t Enter the Number of elements\n"; $n=<STDIN>; $j=0; while($j<$n){ print "\n Enter the $i Element\t"; $arr[$j]=<STDIN>; $j++; } $avg= func_average(@arr); print "\n\tAverage : $avg\n"; $median= func_median(@arr); print "\n\tMedian : $median\n";

UNIX PROGRAMMING

45

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

46

MCA IInd Year IInd Sem

MJCET 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.pl enter two strings mk habeeb no.of lines are: 2 lengthof the string is: 6 upper case letters are: HABEEB lower case letters are: habeeb concatenation of two string is: mk habeeb joining of two strings with number is: habeebmk33

1604-10-862-007

UNIX PROGRAMMING

47

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

48

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{ UNIX PROGRAMMING 49 MCA IInd Year IInd Sem

MJCET print"\tbad luck\n"; }

1604-10-862-007

UNIX PROGRAMMING

50

MCA IInd Year IInd Sem

MJCET output: [root@localhost habib perl progs]# vi 9.pl [root@localhost habib perl progs]# perl 9.pl enter a string habeeb 1) It is a dot pattern match: its got to be habeeb 2) It is [aei] pattern match: its got to be habeeb 3) It is [^aei] pattern match: bad luck 4) It is beginning of shell pattern match: Its got to be habeeb 5) It is end of string pattern match: Its got to be habeeb

1604-10-862-007

UNIX PROGRAMMING

51

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

52

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

53

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: salary Output: 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 old 4. 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 data while (<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 name if ($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 salaries if ($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 people if ($salary > 40000) { $sublist{$name} = $salary; } } } # If there was at least one employee, continue if ($total_employees > 0) { # If there was at least one under 40, continue if ($under_40 > 0) UNIX PROGRAMMING 54 MCA IInd Year IInd Sem

MJCET { $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"; @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 who earned"; 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)

1604-10-862-007

UNIX PROGRAMMING

55

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

56

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 World This is Hello

UNIX PROGRAMMING

57

MCA IInd Year IInd Sem

MJCET ASSIGNMENT - IV

1604-10-862-007

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); UNIX PROGRAMMING 58 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 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));

} }

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); UNIX PROGRAMMING 59 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

// //

write(p1[1],str1,sizeof(str1)); str2 [50] ="Loud and clear"; read(p2[0] ,str2,sizeof(str2)); str2[strlen(str2)]='\0'; printf("\n Process-1(cp) recieves :%s\n",str2); //sleep(3); wait(); printf("\nprocess-1 again sends: %s\n",str3); write(p1[1],str3,sizeof(str3)); //wait();

//

} else if(pid==0) { //sleep(5); close(p1[1]); close(p2[0]); read(p1[0],str1,sizeof(str1)); printf("\n process-2(pp) recieves: %s",str1); wait(); printf("\n Process-2(pp)sends:%s",str2); write(p2[1],str2,sizeof(str2)); wait(); }

//

UNIX PROGRAMMING

60

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

3. Write a server program and two client programs so that the server can communicate privately to each client individually via a single message queue. [mca1002@localhost]~/UNIX/Sockets/EchoServer% cat CO_IT_server.c #include<stdio.h> #include<string.h> #include<errno.h> #include<sys/stat.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> void server_service(int newsockfd); main() { 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); UNIX PROGRAMMING 61 MCA IInd Year IInd Sem

MJCET shutdown(newsockfd,2); } shutdown(sockfd,2); printf("\nENDED CONNECTION....\n");

1604-10-862-007

} void server_service(int newsockfd) { char str[20]; for(;;) { if(read(newsockfd,str,sizeof(str))==-1)perror("UNABLE TO READ FROM CLIENT"); if(write(newsockfd,str,sizeof(str))==-1)perror("ERROR WHILE WRITING"); if(strcmp(str,"BYE")==0) { return; } } } [mca1002@localhost]~/UNIX/Sockets/EchoServer% cat CO_client.c #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> void client_service(int sockfd); main() { 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); UNIX PROGRAMMING 62 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

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); } client_service(sockfd); shutdown(sockfd,2); } void client_service(int sockfd) { char str[20],msg[20]; for(;;) { 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 NUMBER5678 ENTER IP ADDRESS127.0.0.1

UNIX PROGRAMMING

63

MCA IInd Year IInd Sem

MJCET STARTED CONNECTION.... READING FROM CLIENT AT PORT : 41208 SERVICED CLIENT AT PORT : 41208 READING FROM CLIENT AT PORT : 41209 SERVICED 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 : hello hello ENTER MESSAGE OR "BYE" TO EXIT : how how

1604-10-862-007

ENTER MESSAGE OR "BYE" TO EXIT : are are ENTER MESSAGE OR "BYE" TO EXIT : you you ENTER MESSAGE OR "BYE" TO EXIT : bye bye 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 : hello hello

UNIX PROGRAMMING

64

MCA IInd Year IInd Sem

MJCET ENTER MESSAGE OR "BYE" TO EXIT : HOW HOW ENTER MESSAGE OR "BYE" TO EXIT : ARE ARE ENTER MESSAGE OR "BYE" TO EXIT : YOU YOU ENTER MESSAGE OR "BYE" TO EXIT : BYE

1604-10-862-007

[mca1002@localhost]~/UNIX/Sockets/EchoServer%

UNIX PROGRAMMING

65

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. WRITER PROCESS. */ #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/sem.h> #include<string.h> #include<unistd.h> #include<sys/ipc.h> #include<sys/shm.h> FILE *fp; char ch,text[20]; void down(int semid); void up(int semid); void writer(int resource); int main(int argc,char *argv[]) { int wrt,mutex,shmid,pid1,pid2; struct sembuf s; char value[5]; char *msg; wrt=semget(0x10,1,IPC_CREAT|0666); mutex=semget(0x11,1,IPC_CREAT|0666); shmid=shmget((key_t)0x12,10,IPC_CREAT|0666); if(wrt==-1)perror("SEMAPHORE wrt CREATION PROBLEM!"); if(mutex==-1)perror("SEMAPHORE mutex CREATION PROBLEM!"); if(shmid==-1)perror("SHARED MEMORY CREATION PROBLEM!"); semctl(wrt,0,SETVAL,1); semctl(mutex,0,SETVAL,1); msg=shmat(shmid,0,0); strcpy(value,"0"); UNIX PROGRAMMING 66 MCA IInd Year IInd Sem

MJCET strcpy(msg,value); shmdt((char *)msg);

1604-10-862-007

while(1) { writer(wrt); sleep(5); } } void down(int semid) { struct sembuf s; s.sem_num=0; s.sem_op=-1; s.sem_flg=0; semop(semid,&s,1); } void up(int semid) { struct sembuf s; s.sem_num=0; s.sem_op=1; s.sem_flg=0; semop(semid,&s,1); } void writer(int resource) { 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); UNIX PROGRAMMING 67 MCA IInd Year IInd Sem

MJCET printf("WRITER FINISHED WRITING\n"); if(strcmp(text,"BYE")==0) { printf("\n\nWRITER ENDING NOW\n"); up(resource);//signal(wrt) exit(0); } up(resource);//signal(wrt) }

1604-10-862-007

READER PROCESS. #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/sem.h> #include<string.h> #include<unistd.h> #include<sys/ipc.h> #include<sys/shm.h> int readcount=0; FILE *fp; char ch,text[20]; void down(int semid); void up(int semid); void reader(int resource,int mutual,int share); void increment(int *readcount,int shmid); void decrement(int *readcount,int shmid); int main(int argc,char *argv[]) { int wrt,mutex,shmid; struct sembuf s; char *msg; wrt=semget(0x10,1,IPC_CREAT|0666); mutex=semget(0x11,1,IPC_CREAT|0666); shmid=shmget((key_t)0x12,10,IPC_CREAT|0666);

UNIX PROGRAMMING

68

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

if(wrt==-1)perror("SEMAPHORE wrt CREATION PROBLEM!"); if(mutex==-1)perror("SEMAPHORE mutex CREATION PROBLEM!"); if(shmid==-1)perror("SHARED MEMORY CREATION PROBLEM!"); shmdt((char *)msg); reader(wrt,mutex,shmid); }

void down(int semid) { struct sembuf s; s.sem_num=0; s.sem_op=-1; s.sem_flg=0; semop(semid,&s,1); } void up(int semid) { struct sembuf s; s.sem_num=0; s.sem_op=1; s.sem_flg=0; semop(semid,&s,1); } void reader(int resource,int mutual,int share) { while(1) { int i=0; down(mutual);//wait(mutex) increment(&readcount,share);//readcount++; if(readcount == 1) { down(resource); //wait(wrt) } up(mutual);//signal(mutex) printf("\nREADER IS ACTIVE\n"); fp=fopen("file","r"); if(fp==NULL) UNIX PROGRAMMING 69 MCA IInd Year IInd Sem

MJCET { perror("CANNOT OPEN FILE"); exit(0); } i=0; while((ch=fgetc(fp))!=EOF) { text[i]=ch; i++; } text[i]='\0'; printf("%s",text); fclose(fp); printf("\nREADER FINISHED READING\n"); down(mutual);//wait(mutex) decrement(&readcount,share);//readcount--; if(readcount == 0) { up(resource); } //signal(wrt) if(strcmp(text,"BYE")==0) { up(mutual); //signal(mutex) printf("\n\nREADING ENDING NOW\n"); exit(0); } up(mutual); //signal(mutex) sleep(5); } } void increment(int *readcount,int shmid) { int n,rev=0,rem=0,i=0,tempVal; char *msg,value[5]; msg=shmat(shmid,0,0); tempVal=atoi(msg); tempVal++; *readcount=tempVal; n=tempVal; while(n>0) { rem=n%10; UNIX PROGRAMMING 70

1604-10-862-007

MCA IInd Year IInd Sem

MJCET n=n/10; rev=rem+(rev*10); } n=rev; while(n>0) { rem=n%10; n=n/10; switch(rem) { case 0:value[i]='0';break; case 1:value[i]='1';break; case 2:value[i]='2';break; case 3:value[i]='3';break; case 4:value[i]='4';break; case 5:value[i]='5';break; case 6:value[i]='6';break; case 7:value[i]='7';break; case 8:value[i]='8';break; case 9:value[i]='9';break; } i++; } value[i]='\0'; strcpy(msg,value); shmdt((char *)msg); } void decrement(int *readcount,int shmid) { int n,rev=0,rem=0,i=0,tempVal=0; char *msg,value[5]; msg=shmat(shmid,0,0); tempVal=atoi(msg); tempVal--; *readcount=tempVal; n=tempVal; while(n>0) { rem=n%10; n=n/10; rev=rem+(rev*10); UNIX PROGRAMMING 71

1604-10-862-007

MCA IInd Year IInd Sem

MJCET } n=rev; while(n>0) { rem=n%10; n=n/10; switch(rem) { case 0:value[i]='0';break; case 1:value[i]='1';break; case 2:value[i]='2';break; case 3:value[i]='3';break; case 4:value[i]='4';break; case 5:value[i]='5';break; case 6:value[i]='6';break; case 7:value[i]='7';break; case 8:value[i]='8';break; case 9:value[i]='9';break; } i++; } value[i]='\0'; strcpy(msg,value); shmdt((char *)msg); } OUTPUT: SINGLE WRITER:

1604-10-862-007

[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 ACTIVE ENTER SOME TEXT TO BE WRITTEN TO THE FILE hello to all WRITER FINISHED WRITING UNIX PROGRAMMING 72 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

WRITER IS ACTIVE ENTER SOME TEXT TO BE WRITTEN TO THE FILE socket is good WRITER FINISHED WRITING WRITER IS ACTIVE ENTER SOME TEXT TO BE WRITTEN TO THE FILE going to close now WRITER FINISHED WRITING WRITER IS ACTIVE ENTER SOME TEXT TO BE WRITTEN TO THE FILE bye WRITER FINISHED WRITING WRITER IS ACTIVE ENTER SOME TEXT TO BE WRITTEN TO THE FILE BYE WRITER FINISHED WRITING WRITER ENDING NOW READER 1: [mca1002@localhost]~/UNIX/Semaphores% cc Reader.c [mca1002@localhost]~/UNIX/Semaphores% ./a.out READER IS ACTIVE hello to all READER FINISHED READING READER IS ACTIVE socket is good READER FINISHED READING READER IS ACTIVE going to close now READER FINISHED READING READER IS ACTIVE bye READER FINISHED READING UNIX PROGRAMMING 73 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

READER IS ACTIVE BYE READER FINISHED READING READING ENDING NOW READER 2: [mca1002@localhost]~/UNIX/Semaphores% cc Reader.c [mca1002@localhost]~/UNIX/Semaphores% ./a.out READER IS ACTIVE hello to all READER FINISHED READING READER IS ACTIVE socket is good READER FINISHED READING READER IS ACTIVE going to close now READER FINISHED READING READER IS ACTIVE bye READER FINISHED READING READER IS ACTIVE BYE READER FINISHED READING READING ENDING NOW READER 3 JOINED LATER: [mca1002@localhost]~/UNIX/Semaphores% cc Reader.c [mca1002@localhost]~/UNIX/Semaphores% ./a.out READER IS ACTIVE socket is good UNIX PROGRAMMING 74 MCA IInd Year IInd Sem

MJCET READER FINISHED READING READER IS ACTIVE going to close now READER FINISHED READING READER IS ACTIVE bye READER FINISHED READING

1604-10-862-007

READER IS ACTIVE BYE READER FINISHED READING READING ENDING NOW

UNIX PROGRAMMING

75

MCA IInd Year IInd Sem

MJCET 5. write the programs shmget.c, shmctl.c and shmop.c and then

1604-10-862-007

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 o o o

Exchange data between two processe running as shmop.c. Inquire about the state of shared memory with shmctl.c. Use semctl.c to lock a shared memory segment. 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" UNIX PROGRAMMING 76 MCA IInd Year IInd Sem

MJCET #include "sys/types.h" #include "sys/shm.h"

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

77

MCA IInd Year IInd Sem

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

1604-10-862-007

UNIX PROGRAMMING

78

MCA IInd Year IInd Sem

MJCET 7. Write a program to demonstrate file locking. #include<stdio.h> #include<fcntl.h> struct student { int rollno; char name[20]; char add[30]; } s; main() { int fd; fd=open("student.dat",O_WRONLY); write(fd, &s, sizeof(s)); lockf(fd,F_ULOCK,sizeof(s)); } #include<stdio.h> #include<fcntl.h> struct student { int rollno; char name[20]; char add[30]; } s; main() { int fd,t; fd=open("student.dat",O_RDONLY); t=lockf(fd,F_TEST, sizeof(s)); if(t==0) lockf(fd, F_LOCK, sizeof(s)); read(fd,&s,sizeof(s)); printf("%s",s); else printf("File is already locked"); UNIX PROGRAMMING 79

1604-10-862-007

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

80

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

8. Write client/server programs using connection oriented service. Implement server as echo server.

#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> main() { 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 : 7 ENTER IP ADDRESS : 127.0.0.1 UNIX PROGRAMMING 81 MCA IInd Year IInd Sem

MJCET ENTER MESSAGE : hello hello

1604-10-862-007

UNIX PROGRAMMING

82

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

9. Write client/server programs using connection less service. Implement server as Date Timeserver.

#include<errno.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdio.h> #include<sys/stat.h> #include<string.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> main() { 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.out ENTER PORT NUMBER : 13 UNIX PROGRAMMING 83 MCA IInd Year IInd Sem

MJCET ENTER IP ADDRESS : 127.0.0.1 Sun Jun 26 15:03:04 2011

1604-10-862-007

UNIX PROGRAMMING

84

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.

[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% cat CO_IT_server.c #include<stdio.h> #include<errno.h> #include<sys/stat.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #include<unistd.h> #include<fcntl.h> main() { 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); UNIX PROGRAMMING 85 MCA IInd Year IInd Sem

MJCET pid=fork(); if(pid==0) { int fp; FILE *fc;

1604-10-862-007

if(read(newsockfd,filename,sizeof(filename))==-1) perror("UNABLE TO READ SERVER"); strcpy(command,"cc -o ex "); strcat(command,filename); fc=popen(command,"r"); fclose(fc); fp=open("test",O_CREAT|O_WRONLY|O_TRUNC,0666); close(1); if(dup2(fp,1)==-1)perror("ERROR DUP"); if(execl("./ex",(char *)0)==-1)perror("ERROR EXEC"); } else { wait(0); FILE *fp; i=0; fp=fopen("test","r"); if(fp==NULL) write(newsockfd,"COULD NOT EXECUTE",18); else { while((ch=fgetc(fp))!=EOF) { printf("%c",ch); str[i]=ch; i++; } str[i]='\0'; write(newsockfd,str,sizeof(str)); fclose(fp); } } printf("SERVICED CLIENT : %d\n",client); shutdown(newsockfd,2); } }

UNIX PROGRAMMING

86

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

[mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% cat CO_client.c

UNIX PROGRAMMING

87

MCA IInd Year IInd Sem

MJCET #include<errno.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdio.h> #include<sys/stat.h> #include<string.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> main() {

1604-10-862-007

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 : 7000 ENTER IP ADDRESS : 127.0.0.1 UNIX PROGRAMMING 88 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

READING FROM CLIENT : 44739 SUM IS 15 SERVICED CLIENT : 44739 READING FROM CLIENT : 44742 SUM IS 15 SERVICED CLIENT : 44742 ^C CLIENT 1: [mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% cc CO_client.c [mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% ./a.out ENTER PORT NUMBER : 7000 ENTER IP ADDRESS : 127.0.0.1 ENTER FILENAME : sum.c SUM IS 15 CLIENT 2: [mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% cc CO_client.c [mca1002@localhost]~/UNIX/Sockets/RemPrgmExec% ./a.out ENTER PORT NUMBER : 7000 ENTER IP ADDRESS : 127.0.0.1 ENTER FILENAME : sum.c SUM IS 15

UNIX PROGRAMMING

89

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.

#include<string.h> #include<stdlib.h> #include<stdio.h> #include<unistd.h> main() { 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); } else { close(p2[0]); close(p1[1]); read(p1[0],name,sizeof(name)); read(p1[0],passwd,sizeof(passwd)); fp=fopen("user_namepasswd","r"); if(fp==NULL) { perror("ERROR\n"); exit(0); } UNIX PROGRAMMING 90 MCA IInd Year IInd Sem

MJCET else {

1604-10-862-007

while(!feof(fp)) { fscanf(fp,"%s\t%s",nametemp,passwdtemp); if(strcmp(nametemp,name)==0 && strcmp(passwdtemp,passwd)==0) { found=1; write(p2[1],"ACCESS GRANTED",15); break; } } if(found==0) { write(p2[1],"ACCESS DENIED",14); } fclose(fp); } } } OUTPUT: [mca1002@localhost]~/UNIX/Pipes% cat user_namepasswd mca1002 mca1002 mca1003 mca1003 mca1004 mca1004 mca1005 mca1005 mca1006 mca1006 mca1007 mca1007 amatul haiy [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.out ENTER USER NAME : mca1002 ENTER PASSWORD : mca1002 ACCESS GRANTED UNIX PROGRAMMING 91 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

92

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; pipe(p1); pipe(p2); pid=fork(); if(pid==-1) { perror("FAILURE"); } else if(pid!=0) { close(p1[0]); close(p2[1]); printf("ENTER SOURCE FILENAME : "); gets(source); write(p1[1],source,20); read(p2[0],dest,20); printf("%s",dest); } else { 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) UNIX PROGRAMMING 93 MCA IInd Year IInd Sem

MJCET { printf("CANNOT OPEN FILES\n"); write(p2[1],"FAILURE",20); } else { while((ch=fgetc(fpSource))!=EOF) { fputc(ch,fpDest); } write(p2[1],dest,20); } } } OUTPUT: [mca1002@localhost]~/UNIX/Pipes% cat username amatul haiy nazneen atiya

1604-10-862-007

UNIX PROGRAMMING

94

MCA IInd Year IInd Sem

MJCET 14 a. Demonstrate the readv, writev socket system calls /* Advanced socket system calls - readv server */ #include<stdio.h> #include<sys/uio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<stdlib.h> int main() { struct iovec iov[3]; int sockfd,new_sockfd,len,rval; struct sockaddr_in servaddr,cliaddr; char str1[20],str2[20],str3[20]; sockfd=socket(AF_INET,SOCK_STREAM,0); if (sockfd==-1) { perror("Socket creation error"); exit(0); } servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servaddr.sin_port=htons(5678);

1604-10-862-007

rval=bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); if (rval==-1) { perror("Bind Error"); exit(0); } rval=listen(sockfd,5);

UNIX PROGRAMMING

95

MCA IInd Year IInd Sem

MJCET if (rval==-1) { perror("listen error"); exit(0); } iov[0].iov_base=str1; iov[0].iov_len=sizeof(str1); iov[1].iov_base=str2; iov[1].iov_len=sizeof(str2); iov[2].iov_base=str3; iov[2].iov_len=sizeof(str3); len=sizeof(cliaddr); new_sockfd=accept(sockfd,(struct sockaddr *)&cliaddr,&len); if (new_sockfd==-1) { perror("Accept Error"); exit(0); } readv(new_sockfd,&iov[0],3); printf ("\n The data read is : %s %s %s",str1,str2,str3); } /* Advanced socket system calls - writev client*/ #include<stdio.h> #include<sys/uio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<stdlib.h> int main() { struct iovec iov[3]; int sockfd,ret; UNIX PROGRAMMING 96

1604-10-862-007

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

struct sockaddr_in servaddr; char str1[20],str2[20],str3[20]; printf ("\n Enter a string :"); scanf("%s",str1); printf("\n Enter the second string :"); scanf("%s",str2); printf("\n enter the third string"); scanf("%s",str3);

iov[0].iov_base=str1; iov[0].iov_len=sizeof(str1); iov[1].iov_base=str2; iov[1].iov_len=sizeof(str2); iov[2].iov_base=str3; iov[2].iov_len=sizeof(str3);

sockfd=socket(AF_INET,SOCK_STREAM,0); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servaddr.sin_port=htons(5678); ret=connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); if (ret==-1) { perror("Cannot Connect"); exit(0); } writev(sockfd,iov,3); }

UNIX PROGRAMMING

97

MCA IInd Year IInd Sem

MJCET OUTPUT: SERVER:

1604-10-862-007

[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 : 8900 hello to you

14 b. Demonstrate the getpeername, getsockname socket system calls. [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% cat getpeersock.c #include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<stdlib.h> int main() { struct sockaddr_in serv_addr,cli_addr,peer_addr,my_addr; char str[20]; UNIX PROGRAMMING 98 MCA IInd Year IInd Sem

MJCET int port_no,sockfd,new_sockfd,len,rval; char serv[20],msg1[20],msg2[20]; sockfd=socket(AF_INET,SOCK_STREAM,0); rresvport(&port_no); serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(port_no); serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");

1604-10-862-007

if (sockfd==-1) { perror("socket error"); exit(0); } printf("\n Server port number is %d",port_no); fflush(stdout); rval=bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); if (rval==-1) { perror("Cannot Bind"); exit(0); }

rval=listen(sockfd,5); if (rval==-1) { perror("Listen Error"); exit(0); }

while (1) { new_sockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&len); if (new_sockfd==-1) { perror("Accept Error"); exit(0); } getpeername(new_sockfd,(struct sockaddr *)&peer_addr,&len);

UNIX PROGRAMMING

99

MCA IInd Year IInd Sem

MJCET

1604-10-862-007 printf("\n Client port no is : %d",ntohs(peer_addr.sin_port)); printf("\n Address is : %s",inet_ntoa(peer_addr.sin_addr.s_addr)); getsockname(new_sockfd,(struct sockaddr *)&my_addr,&len); printf("\n Server port no is : %d",ntohs(my_addr.sin_port)); printf("\n Address is : %s",inet_ntoa(my_addr.sin_addr.s_addr)); fflush(stdout); read(new_sockfd,msg1,sizeof(msg1)); write(new_sockfd,msg1,sizeof(msg1));

} }

[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% cat client.c #include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<stdlib.h> int main() { int sockfd,ret; struct sockaddr_in servaddr; char str1[20],str2[20]; sockfd=socket(AF_INET,SOCK_STREAM,0); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); servaddr.sin_port=htons(5678); ret=connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); if (ret==-1) { perror("\n Cannot connect"); UNIX PROGRAMMING 100 MCA IInd Year IInd Sem

MJCET exit(0); } 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:

1604-10-862-007

[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% cc getpeersock.c [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% ./a.out ENTER PORT NUMBER : 5678 PEER PORT : 53928 SELF PORT : 5678 CLIENT: [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% cc client.c [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getPeerSockName% ./a.out ENTER PORT NUMBER : 5678 PEER PORT : 5678 SELF PORT : 53928

UNIX PROGRAMMING

101

MCA IInd Year IInd Sem

MJCET 14 c. Demonstrate the getsockopt, setsockopt socket system calls.

1604-10-862-007

[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getsetSockOpt% cat getsetSockOpt.c #include<stdio.h> #include<netinet/in.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/tcp.h> int main() { int sockfd,optval,optlen,max_size; sockfd=socket(AF_INET,SOCK_STREAM,0); optlen=sizeof(optval); if (getsockopt(sockfd,IPPROTO_TCP,TCP_MAXSEG,(char*)&optval,&optlen)<0) perror("get sock error 1"); printf("\n The maximum TCP segment size is %d",optval);

optval=1800; if (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,(char*)&optval,sizeof(optval))<0) perror("set sock error"); if(getsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,(char*)&optval,&optlen)<0) perror("get sock error 2"); printf("\n Send buffer size is %d",optval); } OUTPUT: [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getsetSockOpt% cc getsetSockOpt.c [mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/getsetSockOpt% ./a.out TCP MAXSEG : 536 SEND BUFFER SIZE : 34000 UNIX PROGRAMMING 102 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

103

MCA IInd Year IInd Sem

MJCET 14 d. Demonstrate the socketpair, shutdown socket system calls

1604-10-862-007

[mca1002@localhost]~/UNIX/Sockets/DEMONSTRATION/sockpairShutdown% cat socketpairShutdown.c #include<sys/socket.h> #include<stdio.h> main() { 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

104

MCA IInd Year IInd Sem

MJCET 14 e. Demonstrate the rresvport socket system calls

1604-10-862-007

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

105

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

106

MCA IInd Year IInd Sem

MJCET 15. Write a program to demonstrate asynchronous I/O.

1604-10-862-007

/* Connection Oriented Server */ #include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<stdlib.h> #include<signal.h> #include<fcntl.h> struct sockaddr_in serv_addr,cli_addr; int port_no,len,rval,sockfd,new_sockfd; char serv[20],msg1[20],msg2[20]; void sig_handler();

int main() { struct sockaddr_in serv_addr,cli_addr; char str[20]; int port_no,len,rval,i; char serv[20],msg1[20],msg2[20];

printf("\n Enter the server port number :"); scanf("%d",&port_no); printf("\n Enter the server IP address :"); scanf("%s",serv); serv_addr.sin_port=htons(port_no); serv_addr.sin_addr.s_addr=inet_addr(serv); serv_addr.sin_family=AF_INET; sockfd=socket(AF_INET,SOCK_STREAM,0); if (sockfd==-1) { perror("Cannot create socket"); exit(0); UNIX PROGRAMMING 107 MCA IInd Year IInd Sem

MJCET }

1604-10-862-007

rval=bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); if (rval==-1) { perror("Cannot Bind"); exit(0); } rval=listen(sockfd,5); if (rval==-1) { perror("Listen Error"); exit(0); } len=sizeof(cli_addr); new_sockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&len); if (new_sockfd==-1) { perror("Accept Error"); exit(0); } signal(SIGIO,sig_handler); fcntl(new_sockfd,F_SETOWN,getpid()); fcntl(new_sockfd,F_SETFL,FASYNC); i=1; while (i) { sleep(1); printf("\n%d Waiting for input",i++); } } void sig_handler() { read(new_sockfd,msg1,sizeof(msg1)); printf("\n In server the message received is : %s",msg1); write(new_sockfd,msg1,sizeof(msg1)); UNIX PROGRAMMING 108 MCA IInd Year IInd Sem

MJCET } /* Connection Oriented Client */ #include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<stdlib.h> int main() { struct sockaddr_in serv_addr; char str[20]; int port_no,sockfd,rval; char serv[20],msg1[20],msg2[20];

1604-10-862-007

printf("\n Enter the server port number :"); scanf("%d",&port_no); printf("\n Enter the server IP address :"); scanf("%s",serv); serv_addr.sin_port=htons(port_no); serv_addr.sin_addr.s_addr=inet_addr(serv); serv_addr.sin_family=AF_INET; sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (sockfd==-1) { perror("Socket creation error"); exit(0); } rval=connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); if (rval==-1) { perror("Connection Error"); exit(0); }

UNIX PROGRAMMING

109

MCA IInd Year IInd Sem

MJCET printf("\n Enter the message to send :"); scanf("%s",msg1); write(sockfd,msg1,sizeof(msg1)); read(sockfd,msg2,sizeof(msg2)); printf("\n The message recevied is : %s",msg2); } OUTPUT: SERVER:

1604-10-862-007

[mca1002@localhost]~/UNIX/Sockets/Asynchronous% cc AsyncEchoServer_server.c [mca1002@localhost]~/UNIX/Sockets/Asynchronous% ./a.out ENTER PORT NUMBER8900 STARTED CONNECTION.... SERVER DOING ITS OWN WORK : 0 SERVER DOING ITS OWN WORK : 1 SERVER DOING ITS OWN WORK : 2 READING FROM CLIENT AT PORT : 65535 SERVICED CLIENT AT PORT : 65535 SERVER DOING ITS OWN WORK : 3 CLIENT: [mca1002@localhost]~/UNIX/Sockets/Asynchronous% cc AsyncEchoServer_client.c [mca1002@localhost]~/UNIX/Sockets/Asynchronous% ./a.out ENTER PORT NUMBER : 8900 ENTER MESSAGE : hello hello

UNIX PROGRAMMING

110

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

111

MCA IInd Year IInd Sem

MJCET 16. Write a program to implement the Internet Super server

1604-10-862-007

[mca1002@localhost]~/UNIX/Sockets/Internet% cat InternetSuperServer.c #include<stdio.h> #include<sys/select.h> #include<time.h> #include<string.h> #include<sys/stat.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> void server_service(int newsockfd,int i); main() { 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"); servaddr1.sin_family=AF_INET; servaddr1.sin_port=htons(port1); servaddr1.sin_addr.s_addr=inet_addr(serv); servaddr2.sin_family=AF_INET; servaddr2.sin_port=htons(port2); servaddr2.sin_addr.s_addr=inet_addr(serv); sockfd[0]=socket(AF_INET,SOCK_STREAM,0); sockfd[1]=socket(AF_INET,SOCK_STREAM,0); 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"); UNIX PROGRAMMING 112 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

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) { FD_ZERO(&fs); FD_SET(sockfd[0],&fs); FD_SET(sockfd[1],&fs); select(sockfd[1]+1,&fs,NULL,NULL,NULL); for(i=0;i<=1;i++) { if(FD_ISSET(sockfd[i],&fs)) { len=sizeof(cliaddr); newsockfd=accept(sockfd[i],(struct sockaddr *)&cliaddr,&len); if(newsockfd==-1) { perror("UNABLE TO CONNECT\n"); } pid=fork(); if(pid==0) { client=ntohs(cliaddr.sin_port); printf("\nREADING FROM CLIENT AT PORT : %d",client); server_service(newsockfd,i); printf("\nSERVICED CLIENT AT PORT : %d\n",client); } else { wait(0); shutdown(newsockfd,2); } } } } } void server_service(int newsockfd,int i) UNIX PROGRAMMING 113 MCA IInd Year IInd Sem

MJCET {

1604-10-862-007

char str[20],ch; time_t timer; switch(i) { case 0: if(read(newsockfd,str,sizeof(str))==-1) perror("UNABLE TO READ FROM CLIENT"); if(write(newsockfd,str,sizeof(str))==-1) perror("ERROR WHILE WRITING"); break; case 1: if(read(newsockfd,str,sizeof(str))==-1) perror("UNABLE TO READ FROM CLIENT"); time(&timer); strcpy(str,ctime(&timer)); if(write(newsockfd,str,sizeof(str))==-1) perror("ERROR WHILE WRITING"); break; } } [mca1002@localhost]~/UNIX/Sockets/Internet% cat ECHO_CO_client.c #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> void client_service(int sockfd); main() { 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; UNIX PROGRAMMING 114 MCA IInd Year IInd Sem

MJCET servaddr.sin_port=htons(port); servaddr.sin_addr.s_addr=inet_addr(serv);

1604-10-862-007

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

[mca1002@localhost]~/UNIX/Sockets/Internet% cat DATE_CO_client.c #include<errno.h> #include<sys/socket.h> #include<netinet/in.h> #include<stdio.h> #include<sys/stat.h> #include<string.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> main() { int pid; char ch,filename[20],command[30]; struct sockaddr_in servaddr; int sockfd,newsockfd,port,len; char serv[20],str[20],msg[35]; UNIX PROGRAMMING 115 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

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 : 48669 SERVICED CLIENT AT PORT : 48669

READING FROM CLIENT AT PORT : 37457 SERVICED CLIENT AT PORT : 37457 ^C CLIENT 1 AT ECHO PORT: [mca1002@localhost]~/UNIX/Sockets/Internet% cc ECHO_CO_client.c [mca1002@localhost]~/UNIX/Sockets/Internet% ./a.out UNIX PROGRAMMING 116 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

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 : 6789 ENTER IP ADDRESS : 127.0.0.1 Wed Jun 22 06:52:13

UNIX PROGRAMMING

117

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> <?php echo 'hello'; print '<BR>hello<BR />'; ?> </BODY> </HTML>

UNIX PROGRAMMING

118

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) print $str."&nbsp;and&nbsp;".$str2."&nbsp;are same"; else print $str."&nbsp;and&nbsp;".$str2."&nbsp;are different"; $pos=strpos($str,'lo'); print "<BR>lo at position&nbsp;".($pos+1)."&nbsp;in&nbsp;".$str; $sub=substr($str,3); print "<BR>substr(hello,3) : &nbsp;".$sub; $sub=chop($str); print "<BR>".$sub; ?> </BODY> UNIX PROGRAMMING 119 MCA IInd Year IInd Sem

MJCET </HTML>

1604-10-862-007

3. Write a PHP script to demonstrate number functions


<HTML> <HEAD> <TITLE> DEMO NUMBER FUNCTIONS </TITLE> </HEAD> <BODY> <?php $num=-5.90; print "<BR>CEIL OF&nbsp;".$num."&nbsp;IS&nbsp;".ceil($num); print "<BR>FLOOR OF&nbsp;".$num."&nbsp;IS&nbsp;".floor($num); print "<BR>ABS OF&nbsp;".$num."&nbsp;IS&nbsp;".abs($num); print "<BR>ROUND OF&nbsp;".$num."&nbsp;IS&nbsp;".round($num); $num2=6; print "<BR>MINIMUM OF&nbsp;".$num."&nbsp;and&nbsp;".$num2." &nbsp;IS&nbsp;".min($num,$num2); print "<BR>MAXIMUM OF&nbsp;".$num."&nbsp;and&nbsp;". $num2."&nbsp; UNIX PROGRAMMING 120 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 IS&nbsp;".max($num,$num2); $num=0; $num2=5; print "<BR>RANDOM BETWEEN&nbsp;".$num. "&nbsp;and&nbsp;".$num2."&nbsp;IS&nbsp;".rand(0,5);

?> </BODY> </HTML>

4. Write a PHP script to find the greatest of three numbers


<HTML> <HEAD> <TITLE> LARGEST OF THREE NUMBERS </TITLE> </HEAD> <BODY> <?php $num1=1; $num2=2; $num3=3; UNIX PROGRAMMING 121 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

print "<BR>MAXIMUM OF&nbsp;".$num1."&nbsp;and&nbsp;".$num2. "&nbsp;and&nbsp;". $num3."&nbsp;IS&nbsp;".max($num,max($num2,$num3)); ?> </BODY> </HTML>

UNIX PROGRAMMING

122

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

5. Write a PHP script to create an array, populate the array and display the elements using the foreach statement
<HTML> <HEAD> <TITLE> ARRAY CREATION,POPULATION AND ELEMENT DISPLAY </TITLE> </HEAD> <BODY> <?php $arr=array(10,20,30,40,50); for($i=0;$i<sizeof($arr);$i++) print "<BR>arr[".$i."] :&nbsp;".$arr[$i]; $arr=array("aaa"=>10,"bbb"=>30); print '<BR>'; foreach($arr as $key=>$value) print "<BR>arr[".$key."] :&nbsp;".$value; ?> </BODY> </HTML>

UNIX PROGRAMMING

123

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

6.Write a PHP script to demonstrate the following array functions: unset, array_keys, array_values, sizeof, explode, implode
<HTML> <HEAD> <TITLE> ARRAY set,unset,keys,values,sizeof,implode,explode </TITLE> </HEAD> <BODY> <?php $arr=array(10,20,30,40,50); for($i=0;$i<sizeof($arr);$i++) print "<BR>arr[".$i."] :&nbsp;".$arr[$i]; unset($arr[1]); print '<BR>'; for($i=0;$i<=sizeof($arr);$i++) print "<BR>arr[".$i."] :&nbsp;".$arr[$i]; $arr=array("aaa"=>10,"bbb"=>30); print '<BR>'; foreach($arr as $key=>$value) print "<BR>arr[".$key."] :&nbsp;".$value; print '<BR>'; $key=array_keys($arr); foreach($key as $keyofarr) print "<BR>key [".$keyofarr."]"; print '<BR>'; $value=array_values($arr); foreach($value as $valueofarr) print "<BR>value ".$valueofarr; print '<BR>'; $str=implode(';',$arr); print "<BR>Implode ".$str; print '<BR>'; $arr=explode(';',$str); foreach($arr as $key=>$value) print "<BR>arr[".$key."] :&nbsp;".$value; ?> UNIX PROGRAMMING 124 MCA IInd Year IInd Sem

MJCET </BODY> </HTML>

1604-10-862-007

UNIX PROGRAMMING

125

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

7.Write a PHP script which has a function which accepts an array of numbers and returns the average of these numbers
<HTML> <HEAD> <TITLE> AVERAGE OF NUMBERS OF AN ARRAY </TITLE> <?php function average($arr) { $avg=0; for($i=0;$i<sizeof($arr);$i++) { print "$arr[$i]\t"; $avg=$avg+$arr[$i]; } return $avg/sizeof($arr); } ?> </HEAD> <BODY> <?php $arr=array(10,20,30,40,50); $average=average($arr); print "<BR>average ".$average; ?> </BODY> </HTML>

UNIX PROGRAMMING

126

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

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; } UNIX PROGRAMMING 127 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 $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>"; } ?> </BODY> </HTML>

UNIX PROGRAMMING

128

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

129

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
<HTML> <HEAD> <TITLE> REFERENCE </TITLE> </HEAD> <BODY> <?php print "<H3>"; $num1=$_POST["num1"]; $num2=$_POST["num2"]; $num3=$_POST["num3"]; print "<FORM name='myform' method='POST' action='http://localhost/PHP/reference2.php'>"; print "NUMBER 1 :"; print "<BR>"; print "<input name='num1' type='text' size='10' value=$num1>"; print "<BR>"; print "NUMBER 2 :"; print "<BR>"; print "<input name='num2' type='text' size='10' value=$num2>"; print "<BR>"; print "NUMBER 3 :"; print "<BR>"; print "<input name='num3' type='text' size='10' value=$num3>"; print "<BR>"; print "<input type='submit' value='calculate'>"; maxim($num1,$num2,$num3); function maxim(&$max,$x,$y) { if($max<$x) { $max=$x; } if($max<$y) { $max=$y; } } UNIX PROGRAMMING 130 MCA IInd Year IInd Sem

MJCET print "<BR><BR>maximum : $num1"; print"</FORM>"; print "</H3>"; ?> </BODY> </HTML>

1604-10-862-007

UNIX PROGRAMMING

131

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

132

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

10. PHP SCRIPT TO DEMONSTRATE SCOPE AND LIFETIME OF 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"; function addNumLife() { static $number=1; print "<BR>number : $number"; UNIX PROGRAMMING 133 MCA IInd Year IInd Sem

MJCET $number+=1; } print "<BR>First function call"; addNumLife(); print "<BR>Second function call"; addNumLife(); print "<BR>Third function call"; addNumLife(); print "</H3>"; ?> </BODY> </HTML>

1604-10-862-007

UNIX PROGRAMMING

134

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

135

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.
<?php print "<H2>"; print "preg_match DEMO"; print "</H2>"; print "<H4>"; $string="Hello World!BYE"; print "STRING : $string"; if(preg_match("/^Hello/",$string)) { print "<BR>Hello exists"; } else { print "<BR>Hello doesnt exist"; } print "</H4>"; print "<H2>"; print "preg_split DEMO"; print "</H2>"; print "<H4>"; print "STRING : $string"; $separate=preg_split("/[\s!]/",$string); foreach($separate as $word) print "<BR>$word"; print "</H4>"; ?>

UNIX PROGRAMMING

136

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

137

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

12. Write the html code to accept employee information as follows I) text boxes to accept employee name, roll no, address and salary II) a radio button to accept the type of employee Write a php script that processes the employee information and generates the salary slip
<HTML> <HEAD> <TITLE> EMPLOYEE INFORMATION </TITLE> </HEAD> <BODY> <?php $ename = $_POST["EMPNAME"]; $eno = $_POST["EMPNO"]; $eaddr = $_POST["EMPADDR"]; $esal = $_POST["EMPSAL"]; $etype = $_POST["EMPTYPE"]; $da $hra $TOTAL = = = ($esal*0.05); ($esal*0.10); $esal+$da+$hra;

print "<H3>"; print("EMPLOYEE NUMBER : $eno"); print "</H3>"; print "<H4>"; print "<BR><BR>"; print("$ename,"); print "<BR>"; print("$eaddr,"); print "<BR>"; print("$etype"); print "</H4>"; print "<H2>"; print "<CENTER>EMPLOYEE PAY SLIP</CENTER>"; print "</H2>"; print "<HR color='BLUE'>"; print "<TABLE width='150%'>"; print "<TR> <TD><H3>BASIC</H3></TD> UNIX PROGRAMMING 138 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 <TD><H3>$esal</H3></TD></TR>"; print "<TR> <TD><H3>DA</H3></TD> <TD><H3>$da</H3></TD></TR>"; print "<TR> <TD><H3>HRA</H3></TD> <TD><H3>$hra</H3></TD></TR>"; print "</TABLE>"; print "<HR color='BLUE'>"; print "<H2>"; print("TOTAL SALARY IS $TOTAL"); print "</H2>"; ?> </BODY>

</HTML>

UNIX PROGRAMMING

139

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

UNIX PROGRAMMING

140

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.
<HTML> <HEAD> <TITLE> FEED BACK FORM </TITLE> </HEAD> <BODY BGCOLOR="lightgrey"> <FORM NAME="MYFORM" METHOD="POST" ACTION="http://localhost/PHP/studentServer.php"> <TABLE BORDER="0" HEIGHT="100%" WIDTH="50%" CELLSPACING="0" CELLPADDING="0"> <TR> <TD><STRONG>NAME&nbsp;:&nbsp;</STRONG> <TD><INPUT NAME="NAME" TYPE="TEXT" SIZE=35 MAXLENGTH=20></INPUT> <TR> <TD><STRONG>FATHER'S NAME&nbsp;:&nbsp;</STRONG> <TD><INPUT NAME="FNAME" TYPE="TEXT" SIZE=35 MAXLENGTH=20></INPUT> <TR> <TD><STRONG>ADDRESS&nbsp;:&nbsp;</STRONG> <BR><TEXTAREA NAME="ADDRESS" COLS=50 ROWS=4 WRAP>ENTER THE ADDRESS HERE</TEXTAREA> <TR> <TD><STRONG>HOBBIES&nbsp;:&nbsp;</STRONG> <BR><BR><INPUT NAME="HOBBIES" TYPE="CHECKBOX" VALUE="READING">READING <BR><INPUT NAME="HOBBIES" TYPE="CHECKBOX" VALUE="EATING">EATING <BR><INPUT NAME="HOBBIES" TYPE="CHECKBOX" VALUE="SLEEPING">SLEEPING <BR><INPUT NAME="HOBBIES" TYPE="CHECKBOX" VALUE="SINGING">SINGING <BR><INPUT NAME="HOBBIES" TYPE="CHECKBOX" UNIX PROGRAMMING 141 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 VALUE="DANCING">DANCING <TR> <TD><STRONG>GENDER&nbsp;:&nbsp;</STRONG> <TR> <TD><INPUT NAME="GENDER" TYPE="RADIO" VALUE="MALE" CHECKED>MALE &nbsp; <INPUT NAME="GENDER" TYPE="RADIO" VALUE="FEMALE">FEMALE <TR> <TD><STRONG>OCCUPATION&nbsp;:&nbsp;</STRON G> <TD><SELECT NAME="OCCUPATION" VALUE="OCCUPATION"> <OPTION SELECTED>STUDENT <OPTION>UNEMPLOYED <OPTION>EMPLOYEE </SELECT> <TR> <TD><BR><BR> <TR> <TD><LABEL> <STRONG>EMAIL ID&nbsp;:&nbsp;</STRONG> <TD><INPUT NAME="EID" TYPE="TEXT" SIZE=50 MAXLENGTH=30></INPUT> <TR> <TD><STRONG>PASSWORD&nbsp;:&nbsp;</STRONG> <TD><INPUT NAME="PASSWD" TYPE="PASSWORD" SIZE=15 MAXLENGTH=30></INPUT> <TR> <TD ALIGN="RIGHT"><INPUT TYPE="RESET" VALUE="RESET"></INPUT> <TD ALIGN="LEFT"><INPUT TYPE="SUBMIT" VALUE="SUBMIT"></INPUT> </TABLE> </FORM> </BODY>

</HTML>

UNIX PROGRAMMING

142

MCA IInd Year IInd Sem

MJCET [root@localhost PHP]# cat studentServer.php

1604-10-862-007

<HTML> <HEAD> <TITLE> FEED BACK FORM </TITLE> </HEAD> <BODY BGCOLOR="LIGHTGREY"> <?php $name = $_POST["NAME"]; $fname = $_POST["FNAME"]; $address = $_POST["ADDRESS"]; $gender = $_POST["GENDER"]; $occupation = $_POST["OCCUPATION"]; $eid = $_POST["EID"]; $passwd = $_POST["PASSWD"]; ?> <TABLE BORDER="0" HEIGHT="100%" WIDTH="50%" CELLSPACING="0" CELLPADDING="0"> <TR> <TD><STRONG>NAME&nbsp;:&nbsp;</STRONG> <TD><?php print "$name"; ?> <TR> <TD><STRONG>FATHER'S NAME&nbsp;:&nbsp;</STRONG> <TD><?php print "$fname"; ?> <TR> <TD><STRONG>ADDRESS&nbsp;:&nbsp;</STRONG> <TD><TEXTAREA NAME="ADDRESS" COLS=50 ROWS=4 WRAP><?php print "$address"; ?></TEXTAREA> <TR> <TD><STRONG>GENDER&nbsp;:&nbsp;</STRONG> <TD><?php print "$gender"; ?> <TR> <TD><STRONG>OCCUPATION&nbsp;:&nbsp;</STRONG> <TD><?php print "$occupation"; ?> <TR> <TD><BR><BR> <TR> <TD><LABEL> UNIX PROGRAMMING 143 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 <STRONG>EMAIL ID&nbsp;:&nbsp;</STRONG> <TD><?php print "$eid"; ?> <TR> <TD><STRONG>PASSWORD&nbsp;:&nbsp;</STRONG> <TD><?php print "$passwd"; ?> </TABLE> <?php $fileop='/var/www/html/PHP/student.dat'; $fp=fopen($fileop,'a') or die('cannot open'); if($name=="") fwrite($fp,"NULL"); else fwrite($fp,$name); fwrite($fp,':'); if($name=="") fwrite($fp,"NULL"); else fwrite($fp,$fname); fwrite($fp,':'); if($name=="") fwrite($fp,"NULL"); else fwrite($fp,$address); fwrite($fp,':'); if($name=="") fwrite($fp,"NULL"); else fwrite($fp,$gender); fwrite($fp,':'); if($name=="") fwrite($fp,"NULL"); else fwrite($fp,$occupation); fwrite($fp,"\n"); fclose($fp); ?>

</BODY> </HTML> [root@localhost PHP]# cat studentReader.php UNIX PROGRAMMING 144 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

<HTML> <HEAD> <TITLE> FEED BACK FORM </TITLE> </HEAD> <BODY BGCOLOR="DARKGREY"> <?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

145

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
UNIX PROGRAMMING 146 MCA IInd Year IInd Sem

MJCET

1604-10-862-007

Table.store the details in a file for future reference.


<HTML> <HEAD> <TITLE>CLIENT FORM</TITLE> </HEAD> <BODY> <CENTER><H1>WELCOME TO SAH CANDY STORES</H1></CENTER> <HR COLOR="LIGHTGREY" SIZE="3"> <FORM name="MYFORM" method="POST" action="http://localhost/PHP/superMarketServer.php"> <CENTER><H3>CUSTOMER INFORMATION</H3></CENTER> <TABLE ALIGN="CENTER"> <TR> <TD>Buyer's Name : <TD><INPUT NAME="NAME" TYPE="TEXT" SIZE="20"> <TR> <TD>Street Address : <TD><INPUT NAME="STREET" TYPE="TEXT" SIZE="20"> <TR> <TD>City,State,Pin : <TD><TEXTAREA NAME="CITY_PIN" COLS="20" ROWS="3"> </TEXTAREA> </TABLE> <HR COLOR="LIGHTGREY" SIZE="3"> <CENTER><H3>PRODUCT LISTING</H3></CENTER> <TABLE ALIGN="CENTER" BORDER="7" width="50%"> <TR> <TH>Product Description <TH>Price (in Rs.) <TH>Quantity <TR> <TD>BOURNVILLE <TD ALIGN="CENTER">100.00 <TD ALIGN="RIGHT"><INPUT NAME="ch001" TYPE="TEXT" SIZE="20" VALUE="0"> <TR> UNIX PROGRAMMING 147 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 <TD>DAIRY MILK FRUIT AND NUT <TD ALIGN="CENTER">50.OO <TD ALIGN="RIGHT"><INPUT NAME="ch002" TYPE="TEXT" SIZE="20" VALUE="0"> <TR> <TD>CADBURY CELEBRATIONS <TD ALIGN="CENTER">500.OO <TD ALIGN="RIGHT"><INPUT NAME="ch003" TYPE="TEXT" SIZE="20" VALUE="0"> <TR> <TD>PERK <TD ALIGN="CENTER">10.OO <TD ALIGN="RIGHT"><INPUT NAME="ch004" TYPE="TEXT" SIZE="20" VALUE="0"> <TR> <TD>MUNCH <TD ALIGN="CENTER">20.OO <TD ALIGN="RIGHT"><INPUT NAME="ch005" TYPE="TEXT" SIZE="20" VALUE="0"> </TABLE> <HR COLOR="LIGHTGREY" SIZE="3"> <CENTER><H3>MODE OF PAYMENT</H3></CENTER> <H4> <CENTER> <INPUT NAME="MODE" TYPE="radio" value="MASTER CARD" checked>MASTER CARD <INPUT NAME="MODE" TYPE="radio" value="VISA">VISA <INPUT NAME="MODE" TYPE="radio" value="CHEQUE">CHEQUE </CENTER> </H4> <HR COLOR="LIGHTGREY" SIZE="3"> <CENTER> <INPUT TYPE="SUBMIT" VALUE="SUBMIT DETAILS"> <INPUT TYPE="RESET" VALUE="RESET DETAILS"> </CENTER> </FORM> </BODY> </HTML>

UNIX PROGRAMMING

148

MCA IInd Year IInd Sem

MJCET [root@localhost PHP]# cat superMarketServer.php

1604-10-862-007

<HTML> <HEAD> <TITLE> CLIENT FORM </TITLE> </HEAD> <BODY> <CENTER><H1>SAH CANDY STORES<BR>BILL RECEIPT</H1></CENTER> <HR COLOR="LIGHTGREY" SIZE="3"> <CENTER> <?php print "<H3>CUSTOMER INFORMATION</H3>"; $name = $_POST["NAME"]; print "$name<BR>"; $street = $_POST["STREET"]; print "$street<BR>"; $citypin=$_POST["CITY_PIN"]; print "$citypin<BR>"; $mode=$_POST["MODE"]; $quan1=$_POST["ch001"]; $quan2=$_POST["ch002"]; $quan3=$_POST["ch003"]; $quan4=$_POST["ch004"]; $quan5=$_POST["ch005"]; $price1=100.00; $price2=50.00; $price3=500.00; $price4=10.00; $price5=20.00; if($quan1=="")$quan1=0; if($quan2=="")$quan2=0; if($quan3=="")$quan3=0; if($quan4=="")$quan4=0; if($quan5=="")$quan5=0; ?> </CENTER> <HR COLOR="LIGHTGREY" SIZE="3"> UNIX PROGRAMMING 149 MCA IInd Year IInd Sem

MJCET

1604-10-862-007 <CENTER> <H3>ORDER INFORMATION</H3> </CENTER> <TABLE BORDER="7" width="75%" ALIGN="CENTER"> <TR> <TH>Product Code <TH>Product Description <TH>Price (in Rs.) <TH>Quantity <TH>Item Cost (in Rs.) <TR> <TD>ch001 <TD>BOURNVILLE <TD ALIGN="CENTER">100.00 <TD ALIGN="CENTER"><?php print "$quan1"; ?> <TD ALIGN="RIGHT"> <?php $item_cost1=$quan1*$price1; print "$item_cost1"; ?> <TR> <TD>ch002 <TD>DAIRY MILK FRUIT AND NUT <TD ALIGN="CENTER">50.OO <TD ALIGN="CENTER"><?php print"$quan2"; ?> <TD ALIGN="RIGHT"> <?php $item_cost2=$quan2*$price2; print "$item_cost2"; ?> <TR> <TD>ch003 <TD>CADBURY CELEBRATIONS <TD ALIGN="CENTER">500.OO <TD ALIGN="CENTER"><?php print"$quan3"; ?> <TD ALIGN="RIGHT"> <?php $item_cost3=$quan3*$price3; print "$item_cost3"; ?> <TR> <TD>ch004 <TD>PERK

UNIX PROGRAMMING

150

MCA IInd Year IInd Sem

MJCET

1604-10-862-007 <TD ALIGN="CENTER">10.OO <TD ALIGN="CENTER"><?php print"$quan4"; ?> <TD ALIGN="RIGHT"> <?php $item_cost4=$quan4*$price4; print "$item_cost4"; ?> <TR> <TD>ch005 <TD>MUNCH <TD ALIGN="CENTER">20.OO <TD ALIGN="CENTER"><?php print"$quan5"; ?> <TD ALIGN="RIGHT"> <?php $item_cost5=$quan5*$price5; print "$item_cost5"; ?> </TABLE> <BR> <BR> <BR> <BR> <HR COLOR="LIGHTGREY" SIZE="3"> <CENTER> <H3>PAYMENT DETAILS</H3> <?php $total_price=$item_cost1+$item_cost2+$item_cost3+ $item_cost4+$item_cost5; $total_qty=$quan1+$quan2+$quan3+$quan4+$quan5; 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,":");

UNIX PROGRAMMING

151

MCA IInd Year IInd Sem

MJCET

1604-10-862-007 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); 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>

UNIX PROGRAMMING

152

MCA IInd Year IInd Sem

MJCET [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>

1604-10-862-007

UNIX PROGRAMMING

153

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

15. Write a php script to demonstrate cookies.


<HTML> <HEAD> <?php // // ?> <?php if(IsSet($_COOKIE["visited"])) { print "welcome again"; } else { print "welcome"; } ?> <TITLE> COOKIE DEMONSTRATION </TITLE> </HEAD> <BODY> </BODY> </HTML> setcookie("visited","true",time()+5000); undefines cookie setcookie("visited","",time()+5000);

UNIX PROGRAMMING

154

MCA IInd Year IInd Sem

MJCET

1604-10-862-007

16. Write a php script to demonstrate server side session Tracking.


<HTML> <HEAD> <?php session_start(); if(!IsSet($_SESSION["page_num"])) { $_SESSION["page_num"]=1; } $page_num=$_SESSION["page_num"]; print "you have visited this page $page_num pages<BR>"; $_SESSION["page_num"]++; ?> <TITLE> SESSION DEMONSTRATION </TITLE> </HEAD> <BODY> </BODY> </HTML>

UNIX PROGRAMMING

155

MCA IInd Year IInd Sem

S-ar putea să vă placă și