Sie sind auf Seite 1von 97

Unix Programming Lab 2011

Mount Carmel College (Autonomous)


No 58, Palace Road, Bangalore-52

Unix/Linux Lab Record Department of MCA


(III Semester)

Batch: 2010 to 2013

Submitted By Name: Divya T.S Register No: M10MC09

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Mount Carmel College (Autonomous)


No 58, Palace Road, Bangalore-52

Certificate

This is to certify that DIVYA T.S [M10MC09] has satisfactorily completed the course of practical assignment in UNIX/LINUX LAB prescribed by Mount Carmel College (Autonomous), Bangalore affiliated to Bangalore University and approved by AICTE for the III semester of MCA for the year 2011-2012.

Lecturer In-charge

Coordinator of MCA

Date of Examination:

Signature of the Examiners:

Seal of the center

1.

2.

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Table of Contents

SL. NO.

DATE

PROGRAMS

PAGE NO.

SECTION - A
1 Shell script to demonstrate File Manipulation

2 3

Shell script to demonstrate Directory File Operation Shell script for String Manipulation

Shell Script to check whether given input is alphabet, digit, and special characters Shell script to generate an electricity bill according to the details given below in proper bill format

Shell script to implement Database Operations (any domain) which includes

SECTION - B
7 Program to print environmental variables

8 9

Program to print all process ids Demonstrate process creation using fork ()

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

10 11 12 13

Program to open, read, write using system call Program to demonstrate process without locking Program to implement Pipes Program to illustrate IPC

14

Program to implement cat command simulation

15 16

Program to demonstrate Message Queues Program to demonstrate FIFO

17

Program to demonstrate TCPClient/TCPServer

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Program:1 Date

Shell script to demonstrate File Manipulation

clear c="y" while [ $c = y ] do clear echo "menu selection" echo "1.File creation" echo "2.File display" echo "3.File rename" echo "4.File delete" echo "5.File append" echo "6.Copy one file to another file". echo "7.File permission". echo "8.Exit" echo "enter ur choice" read ch case $ch in 1) echo "enter file name(to create)" read fname if [ -f $fname ] then echo "file exits" else echo "enter data into a file" echo "press ctr+d to end" cat>$fname

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

echo "file created" fi;; 2) echo "enter file name" read fname if [ -f $fname ] then echo "the file $fname contents" cat $fname else echo "file does not exit" fi;; 3) echo "enter file name(to rename)" read fname echo "enter name to rename" read dname if [ -f $fname ] then mv $fname $dname echo "$fname file renamed to $dname" else echo "file does not exit" fi;; 4) echo "enter file name to delete" read fname if [ -f $fname ] then rm $fname echo "filedeleted"

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

else echo "file does not exit" fi;; 5) echo "Enter a file name" read fn if [ -f $fn ] then echo "File exists" echo "Enter a text in to a file" echo "Press ctrl-d to end" cat>>$fn echo "File appended" else echo "File not exists" fi;; 6) echo "Enter a source file to copy" read sf echo "Enter a destination file to copy" read df if [ -f $sf ] then echo "File exits" cp $sf $df echo "File copied" else echo "file does not exist" fi ;; 7) echo "enter file name"

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

read name if [ -f $name ] then echo "entered file is a regular file" echo "enter the class(user|group|others)" echo "enter u|g|o" read c case $c in U|u) echo "enter permission(read|write|execute)" echo "enter r|w|x" read p case $p in R|r) chmod u+r $name echo "read permissions to user class";; W|w) chmod u+w $name echo "write permissions to user class";; X|x) chmod u+x $name echo "execute permissions to user class";; *) esac;; echo "not a valid input"

G|g)

echo "enter permissions(read|write|execute)" echo "enter r|w|x" read p case $p in R|r) chmod g+r $name echo "read permissions to group class";; W|w) chmod g+w $name echo "write permissions to group class";; X|x) chmod g+x $name echo "execute permissions to group class";;

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

*) esac;;

echo "not a valid input";;

O|o) echo "enter permissions(read|write|execute)" echo "enter r|w|x" read p case $p in R|r) chmod o+r $name echo "read permissions to other class";; W|w) chmod o+w $name echo "write permissions to other class";; X|x) chmod o+x $name echo "execute permissions to other class";; *) esac;; echo "not a valid input";;

*) esac else

echo "not a valid class"

echo "file does not exist" fi ls -l ;; 8) *) esac echo do you wish to continue? read c done exit;; echo "file does not exist"

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

*************************************************** Menu selection *************************************************** 1.File creation 2.File display 3.File rename 4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8.Exit Enter ur choice : 1 Enter file name(to create) : filedemon enter data into a file press ctr+d to end This is unix programming.It is easy to learn and understand. file created do you wish to continue? Y *************************************************** Menu selection *************************************************** 1.File creation

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

2.File display 3.File rename 4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8.Exit enter ur choice : 2 Enter file name : File demon The file filedemon contents This is UNIX programming. It is easy to learn and understand. do you wish to continue? Y *************************************************** Menu selection *************************************************** 1.File creation 2.File display 3.File rename 4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8.Exit Enter ur choice : 3

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

enter file name(to rename) : filedemon enter name to rename : newfile filedemon file renamed to newfile do you wish to continue?Y *************************************************** Menu selection *************************************************** 1.File creation 2.File display 3.File rename 4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8.Exit Enter Ur choice: 4 Enter file name to delete file1 file deleted do you wish to continue?Y *************************************************** Menu selection *************************************************** 1.File creation 2.File display 3.File rename

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8.Exit Enter ur choice : 5 Enter a file name : newfile File exists Enter a text in to a file Press ctrl-d to end i love unix programming.it is interesting File appended do you wish to continue?Y *************************************************** Menu selection *************************************************** 1.File creation 2.File display 3.File rename 4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8.Exit Enter ur choice : 6

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Enter a source file to copy : newfile Enter a destination file to copy : destfile File exits File copied do you wish to continue? Y *************************************************** Menu selection *************************************************** 1.File creation 2.File display 3.File rename 4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8. Exit Enter ur choice: 7 Enter file name : newfile Entered file is a regular file Enter the class(user|group|others) Enter u|g|o g Enter permissions(read|write|execute) Enter r|w|x

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

w -rw-rw-r-- 1 m10mc09 m10mc09 -rwxrwxr-x 1 m10mc09 m10mc09 178 Aug 31 15:05 envir.c 11582 Aug 31 15:05 envir.out 109 Jul 27 09:40 extract 1288 Aug 5 15:14 f1 1711 Aug 5 15:26 f2 72 Aug 5 15:30 f3 109 Jul 22 10:36 file 47 Sep 7 15:05 filedemo 560 Aug 26 15:26 fileopen 524 Aug 26 15:40 fileopen.c 12440 Aug 26 15:29 fileopen.out 1298 Sep 7 14:56 filepg 464 Sep 7 14:57 fileprg 103 Sep 7 15:18 files 0 Jul 20 09:22 hello 28 Aug 26 16:23 hosp 3046 Aug 31 14:58 hospit 3002 Aug 31 15:01 hospital 557 Aug 31 15:43 ipc.c 1096 Aug 7 13:18 labdir 2848 Sep 7 15:00 labfile 5981 Aug 4 15:33 labstr 5636 Aug 5 16:01 labstring 76 Jul 13 10:01 leng

-rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rwxrwxr-x 1 m10mc09 m10mc09

-rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

-rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rwxrwxr-x 1 m10mc09 m10mc09

140 Jul 27 10:21 list 52 Aug 3 15:19 myfile 50 Aug 3 15:22 myfile.c 11535 Aug 3 15:24 myfile.out 37 Jul 13 10:13 new1 103 Sep 7 15:17 newfile 169 Jul 8 10:47 prev 1622 Aug 31 15:07 processid 1622 Aug 31 15:08 processid.c 13138 Aug 31 15:09 processid.out 29 Aug 26 15:58 qqq 111 Jul 27 10:01 replace 29 Jul 22 09:26 result 137 Jul 27 10:52 rev 12 Jul 22 09:18 s1 16 Jul 22 09:15 s2 169 Jul 8 10:44 samp 169 Jul 8 10:43 sample 1 Aug 31 15:45 SEQFILE 48 Jul 13 09:30 simple 29 Jul 22 10:16 ss 6 Aug 5 15:59 str 26 Aug 28 15:18 stud 30 Jul 20 09:45 work

-rw-rw-r-- 1 m10mc09 m10mc09 -rwxrw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rwxrwxr-x 1 m10mc09 m10mc09

-rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09 -rw-rw-r-- 1 m10mc09 m10mc09

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

do you wish to continue? : Y

*************************************************** Menu selection *************************************************** 1.File creation 2.File display 3.File rename 4.File delete 5.File append 6.Copy one file to another file. 7.File permission. 8.Exit Enter ur choice : 8

PROGRAM EXITS

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Program :2 Date

Shell script to demonstrate Directory File Operations

# Directory Manupulation clear echo "___________________________" echo echo "DIRECTORY MANUPULATION" echo "___________________________" wish="y" until [ $wish = "n" ] do echo echo 1.Listing directory echo 2.Create a new directory echo 3.Copy from one directory to another echo 4.Rename a Directory echo 5.Delete a directory echo echo "enter ur choice" read ch echo case $ch in 1) echo Listing Directories Echo

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

for i in * do if [ -d $i ] then echo $i fi done;; 2) echo Create a new directory echo echo Enter the directory name read dirt if [ -d $dirt ] then echo Directory already exists else mkdir $dirt echo Directory created fi ;; 3) echo Copy the contents of directories echo echo Enter the source and target directory read dr1 dr2 if [ -d $dr1 -a -r $dr1 -a -w $dr1 ] then if [ -d $dr2 -a -w $dr2 ]

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

then echo Both directory exists with read write Permissions echo cp -r $dr1 $dr2 echo Copied Successfully else echo Target doesnt exist,creating new directory echo cp -r $dr1 $dr2 echo Copied Successfully fi else echo echo Source directory does not exists with read write permission fi;; 4) echo Rename / move a directory echo echo Enter the source and target directory read dr1 dr2 if [ -d $dr1 -a -r $dr1 -a -w $dr1 -a -x $dr1 ] then if [ -d $dr2 -a -r $dr1 -a -w $dr1 -a -x $dr1 ] then echo Source and Target directory exists with Permissions echo

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

mv $dr1 $dr2 echo Moved Successfully else echo Target does not exist with permissions fi else echo Both directory does not exists with correct permissions fi;; 5) echo To delete a directory echo echo Enter the directory to delete read dr if [ -d $dr -a -r $dr -a -x $dr ] then rm -ir $dr echo Directory deleted else echo Directory does not exists with correct permissions fi;; esac echo echo "Do you wish to continue(y/n)? " read wish done

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory

Enter ur choice: 1 ************************************************** Listing Directories ************************************************** divya div dir3 newdir1 Do you wish to continue(y/n)? Y 1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory

Enter ur choice :2

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

************************************************** Create a new directory ************************************************** Enter the directory name :newdir2 Directory created Do you wish to continue(y/n)? y

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory

Enter ur choice :3 ************************************************** Copy the contents of directories ************************************************** Enter the source and target directory divya dir3 Both directory exists with read write Permissions Copied Successfully Do you wish to continue(y/n)?y

1.Listing directory 2.Create a new directory

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory Enter ur choice:2 ************************************************** Create a new directory ************************************************** Enter the directory name divya Directory already exists Do you wish to continue(y/n)?Y

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory

Enter ur choice:3 Copy the contents of directories Enter the source and target directory divya newd Target doesnt exist,creating new directory Copied Successfully Do you wish to continue(y/n)?y

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory Enter ur choice:3 ************************************************** Copy the contents of directories ************************************************** Enter the source and target directory d1 dir3 Source directory does not exists with read write permission Do you wish to continue(y/n)?Y

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory Enter ur choice:4 ************************************************** Rename / move a directory ************************************************** Enter the source and target directory divya div

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Both directory does not exists with correct permissions Do you wish to continue(y/n)?y

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory Enter ur choice:4 ************************************************** Rename / move a directory ************************************************** Enter the source and target directory dir3 newdir1 Source and Target directory exists with Permissions Moved Successfully Do you wish to continue(y/n)?Y

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory Enter ur choice:5

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

************************************************** Delete a directory ************************************************** Enter the directory to delete :div rm: remove directory `anu'? y Directory deleted Do you wish to continue(y/n)?y

1.Listing directory 2.Create a new directory 3.Copy from one directory to another 4.Rename a Directory 5.Delete a directory enter ur choice :5 ************************************************** To delete a directory ************************************************** Enter the directory to delete :divya rm: descend into directory ` divya'? y rm: remove regular empty file ` divya/fil1'? y rm: remove regular empty file ` divya/fil2'? y rm: remove directory ` divya'? y Directory deleted Do you wish to continue(y/n)?N

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Program :3 Date

Shell script to demonstrate String Manipulation

#String program until [ $wish = 'n' -o $wish = 'n' ] do tput clear tput cup 10 0 echo ==================================== echo " String Manipulation "

echo ==================================== echo echo Choose from menu echo ---------------echo 1.Length echo 2.Substring echo 3.Replace echo 4.Delete echo 5.Using String Array echo echo Enter your choice : read ch case $ch in 1) echo Enter the string cat > str len=`wc -c str | awk '{ print $1 }'` l=`expr $len - 1`

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

echo echo the length of the string is $l ;; 2) echo Enter the string cat > str echo Enter the position to extract read p echo enter the number of characters to extract from the position read num l=`wc -c str | awk '{print $1}'` l=`expr $l - 1` n=`expr $p + $num` if [ $n -gt $l ] then echo not possible else ch="" i=1 while [ $i -le $num ] do ch1=`cut -c $p str` ch=$ch$ch1 let i++ let p++ done echo $ch fi ;;

3)

echo Enter the String

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

read str str="$str" echo enter which str to replace read r echo enter new string to replace read w rstr="${str//$r/$w}" echo $rstr ;; 4) echo Enter the String read str str="$str" echo enter the str to delete read d dstr="${str//$d/ }" echo $dstr ;;

5)

until [ $wish = 'n' -o $wish = 'n' ] do tput clear tput cup 10 0 echo ==================================== echo " String Manipulation using Array " echo ==================================== echo echo 1.Create echo 2.insert echo 3.search

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

echo 4.Delete echo echo enter your choice: read choice case $choice in 1) array={} echo how many read n i=0 echo enter the elements while [ $i -lt $n ] do read array[$i] let i++ done i=0 while [ $i -lt $n ] do echo "$i : ${array[$i]}" let i++ done ;; 2) echo ento "Enter the element to insert:" read item echo "Enter the position to insert:" read pos pos=`expr $pos - 1` j=`expr $n - 1` i=$j

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

while [ $i -ge $pos ] do k=`expr $i + 1` temp="${array[$i], }" array[$k]=$temp i=`expr $i - 1` done array[$pos]=$item echo "The contents of the after insertion are:" n=`expr $n + 1` echo "${array[@], }" ;; 3) echo echo the elements are echo ---------------echo i=0 while [ $i -lt $n ] do echo "$i : ${array[$i]}" let i++ done echo echo enter element to search read item i=0 while [ $i -lt $n ] do a=${array[$i]} if [ $a = $item ]

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

then echo $item is present at position $i break else let i++ fi done ;; 4) echo "Enter the position of the element to delete:" read pos1 pos1=`expr $pos1 - 1` array[$pos1]="" echo "${array[@], }" ;; esac echo continue read wish done ;; esac echo echo "Continue the program again??" read wish done

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

==================================== String Manipulation ==================================== Choose from menu --------------------------1. Length 2. Substring 3. Replace 4. Delete 5. Using String Array

Enter your choice: 1 Enter the string i am good The length of the string is 9 Continue the program again??Y ==================================== String Manipulation ==================================== Choose from menu ---------------1.Length 2.Substring

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

3.Replace 4.Delete 5.Using String Array

Enter your choice: 2 Enter the string: i am good Enter the position to extract 3 Enter the number of characters to extract from the position: 4 am g Continue the program again??Y

==================================== String Manipulation ==================================== Choose from menu ---------------1. Length 2. Substring 3. Replace 4. Delete 5. Using String Array

Enter your choice: 3 Enter the String : i am good Enter which str to replace : good

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Enter new string to replace : fine i am fine Continue the program again??Y

==================================== String Manipulation ====================================

Choose from menu ---------------1. Length 2. Substring 3. Replace 4. Delete 5. Using String Array

Enter your choice:4 Enter the String i am very happy Enter the str to delete very i am happy

Continue the program again??Y

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Choose from menu ---------------1.Length 2.Substring 3.Replace 4.Delete 5.Using String Array

Enter your choice :5 ==================================== String Manipulation using Array ====================================

1.Create 2.insert 3.search 4.Delete

Enter your choice:1 How many :4 Enter the elements divya anu dexi saranya

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

0 : divya 1 : anu 2 : dexi 3 : saranya continue y

==================================== String Manipulation using Array ====================================

1.Create 2.insert 3.search 4.Delete

Enter your choice:2 Enter the element to insert: poornima Enter the position to insert:3 The contents of the after insertion are: divya anu poornima

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

dexi saranya continue : y

==================================== String Manipulation using Array ====================================

1.Create 2.insert 3.search 4.Delete

Enter your choice:3

The elements are ---------------0 : divya 1 : anu 2 : poornima 3 : dexi 4 : saranya

Enter element to search :saranya saranya is present at position 4

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

continue y

==================================== String Manipulation using Array ====================================

1.Create 2.insert 3.search 4.Delete

Enter your choice:4 Enter the position of the element to delete:3 divya anu dexi saranya continue n Continue the program again?? n

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Program :4 Date

Shell script to demonstrate whether the entered key is a character,number or special character

echo echo "************************************" echo " Check the character that is typed" echo "************************************* wish="y" until [ $wish = "n" ] do echo "Enter the character" read ch case $ch in [0-9]) echo echo "----------------" echo "$ch is a number" echo "----------------" ;; [A-Z]) echo echo "----------------------------" echo "$ch is a upper case alphabet" echo "----------------------------"

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

;; [a-z]) echo echo "-----------------------------" echo "$ch is a lower case alphabet" echo "-----------------------------" ;; ?) echo echo "-----------------------------------" echo "You entered a special character $ch" echo "-----------------------------------" ;; *) echo echo echo Wrong entry!! ;; esac echo echo echo "Do u wish to continue(y/n)" read wish done read wish done

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

************************************ Check the character that is typed ************************************ Enter the character :3 ---------------3 is a number ---------------Do u wish to continue(y/n) :y

Enter the character :G ---------------------------G is a upper case alphabet ---------------------------Do u wish to continue(y/n) :y

Enter the character :s ---------------------------s is a lower case alphabet ---------------------------Do u wish to continue(y/n) :y Enter the character :!

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

----------------------------------You entered a special character ! ----------------------------------Do u wish to continue(y/n) :y

Enter the character & ----------------------------------You entered a special character & ----------------------------------Do u wish to continue(y/n) n

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Program :5 Date

Shell script to generate an electricity bill

# Electricity Bill c=0 c1=0 c2=0 con=" " echo Enter the name read name echo Enetr the address read add echo Enetr the previous reading read prev echo Enter the current reading read cur unit=`expr $cur - $prev` echo ---------------------echo 1. Domestic use echo 2. Small scale echo 3. Large scale echo ---------------------echo Enetr the type of connection

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

read op case $op in 1) con="Domestic Use" if [ $unit -ge 100 ] then q=`expr $unit - 100` c=`expr 100 \* 1` if [ $q -ge 500 ] then q1=`expr $q - 500` c1=`expr 500 \* 2` c2=`expr $q1 \* 3` else c1=`expr $q \* 2` fi else c=`expr $unit \* 1` fi sum=`expr $c + $c1 + $c2` ;; 2) con="Small scale" if [ $unit -ge 100 ] then

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

q=`expr $unit - 100` c=`expr 100 \* 2` if [ $q -ge 500 ] then q1=`expr $q - 500` c1=`expr 500 \* 3` c2=`expr $q1 \* 4` else c1=`expr $q \* 3` fi else c=`expr $unit \* 2` fi sum=`expr $c + $c1 + $c2` ;; 3) con="Large scale" if [ $unit -ge 100 ] then q=`expr $unit - 100` c=`expr 100 \* 3` if [ $q -ge 500 ] then q1=`expr $q - 500` c1=`expr 500 \* 4`

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

c2=`expr $q1 \* 5` else c1=`expr $q \* 3` fi else c=`expr $unit \* 1` fi

sum=`expr $c + $c1 + $c2` ;; *) echo invalid ;; esac clear echo "***********************************************" echo " Name echo "Adress : $name" : $add"

echo "Connection Type : $con" echo "Previous Reading : $prev" echo "Current Reading : $cur" echo "Units Consumed : $unit"

echo "***********************************************" echo "Total Amount : Rs.$sum"

echo "***********************************************"

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

Enter the name :Divya Enetr the address :#34 1st cross Bangalore Enetr the previous reading :600 Enter the current reading :1000 ---------------------1. Domestic use 2. Small scale 3. Large scale ---------------------Enter the type of connection: 1 *********************************************** Name Adress : Divya : #34 1st cross Bangalore

Connection Type : Domestic Use Previous Reading : 600 Current Reading : 1000 Units Consumed : 400

*********************************************** Total Amount : Rs.700

*********************************************** Enter the name :Anu Enter the address :#21, cunningham road, banglore-3 Enter the previous reading :500

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Enter the current reading :1500 ---------------------1. Domestic use 2. Small scale 3. Large scale ---------------------Enetr the type of connection :2 *********************************************** Name Adress : divya : #21, cunningham road, banglore-3

Connection Type : Small scale Previous Reading : 500 Current Reading : 1500 Units Consumed : 1000

*********************************************** Total Amount : Rs.3300

*********************************************** --------------------Electricity Bill --------------------Enter the name :saranya Enetr the address :#89, 1st street, RV layout, banglore Enetr the previous reading :2000 Enter the current reading :3448

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

---------------------1. Domestic use 2. Small scale 3. Large scale ---------------------Enetr the type of connection :3 *********************************************** Name Adress : saranya : #89, 1st street, RV layout, banglore

Connection Type : Large scale Previous Reading : 2000 Current Reading : 3448 Units Consumed : 1448

*********************************************** Total Amount : Rs.6540

***********************************************

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Program :6 Date

Shell script to demonstrate Database Program

clear i="y" echo echo "************************************************************************" echo " DATABASE PROGRAM "

echo "************************************************************************" echo echo "Enter name of database " read db while [ $i = "y" ] do clear echo echo "************************************************************************" echo echo " echo echo "************************************************************************" echo "1. Add Records " echo MENU SELECTION "

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

echo "2. Display Records" echo echo "3. Search for Specific Records " echo echo "4. Update Record " echo echo "5. Delete Records " echo echo "6.Exit" echo echo echo echo "Enter your choice " read ch case $ch in 1) clear echo "************************************************************" echo echo " echo echo "************************************************************" echo echo "Enter new Patient id " read tid echo "Enter new name:" ADDING NEW RECORD "

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

read tnm echo "Enter address " read des echo "Enter phone_no" read ph echo "$tid $tnm $des $ph">>db;;

2)clear echo "************************************************************" echo echo "PATIENT_ID NAME ADDRESS PHONE_NO echo echo "************************************************************" cat db echo echo "************************************************************";; "

3) clear echo " echo echo "Enter id " read id echo "************************************************************" echo echo " PATIENT_ID NAME ADDRESS PHONE_NO " SEARCH "

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

echo echo "************************************************************" echo grep -i "$id" db echo "************************************************************";;

4)echo "Enter Id" read id grep -i "$id" db echo grep -v "$id" db > dbs2 mv dbs2 db echo "Enter new std id " read tid echo "Enter new name:" read tnm echo "Enter address " read des echo "Enter phone no" read college echo "$tid $tnm $des $ph">>db;;

5)clear echo echo "************************************************************"

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

echo echo " echo echo "************************************************************" echo echo "Enter Id" read id grep -v "$id" db > dbs1 echo "Record is deleted" cat dbs1 mv dbs1 db;; DELETING RECORD "

6)exit;; *)echo "Invalid choice " ;; esac echo "Do u want to continue ?" read i if [ $i != "y" ] then exit fi done

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:1 Date:

Program to print environmental variables

#include <stdio.h> main(argc,argv,envp) int argc; char *argv[]; char *envp[]; { int i; for(i=0;envp[i]!=(char*)0;i++) printf("%s\n",envp[i]); }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT
[m10mc09@linuxserver m10mc09]$ gcc -o envir.out envir.c [m10mc09@linuxserver m10mc09]$ ./envir.out REMOTEHOST=192.168.3.98 HOSTNAME=linuxserver SHELL=/bin/bash TERM=ansi HISTSIZE=1000 USER=m10mc09 LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd=40;33;01:cd=40;33;0 tm=01;32:*.bat=01;32:*.sh=01;32:*.csh=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31: *.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:* .bz=01;31:*.tz=01;31:*.rpm=01;31:*.cpio=01;31:*.jpg=01;35:*.gif=01;35:*.bmp=01;3 5:*.xbm=01;35:*.xpm=01;35:*.png=01;35:*.tif=01;35: MAIL=/var/spool/mail/m10mc09 PATH=/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/m10mc09/bin INPUTRC=/etc/inputrc PWD=/home/m10mc09 LANG=en_US.UTF-8 SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass SHLVL=1 HOME=/home/m10mc09 LOGNAME=m10mc09 LESSOPEN=|/usr/bin/lesspipe.sh %s G_BROKEN_FILENAMES=1_=./envir.out

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:2 Date:

Program to print all process Ids

#include<stdio.h> int main() { char chh; int ch; int i; do { printf("\n ******************"); printf("\n The different IDs"); printf("\n******************"); printf("\n1.Process id"); printf ("\n2.Parent process id"); printf("\n3.Realgroup id"); printf("\n4.Effective group id"); printf("\n5.Real user id"); printf("\n6.Effective user id"); printf("\nEnter the choice\n"); scanf("%d",&ch); switch(ch) {

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

case 1: i=getpid(); printf("\n The process id is %d\n",i); break;

case 2: i=getppid(); printf("\n The parent process id is %d\n",i); break;

case 3: i=getgid(); printf("\n The real group id is %d\n",i); break;

case 4: i=getegid(); printf("\n The effective group id is %d\n",i); break;

case 5: i=getuid(); printf("\n The real user id is %d\n",i); break;

case 6: i=geteuid(); printf("\n The effective user id is %d\n",i); break;

default:printf("\n Wrong Choioce!!!!");

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

break; } printf("Do u wish to continue? (y/n)"); scanf("%c",&chh); scanf("%c",&chh);

}while(chh=='y' || chh=='Y'); //getch(); }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

****************** The different IDs ****************** 1.Process id 2.Parent process id 3.Realgroup id 4.Effective group id 5.Real user id 6.Effective user id Enter the choice 2 The parent process id is 8939 Do u wish to continue? (y/n)y ****************** The different IDs ****************** 1.Process id 2.Parent process id 3.Realgroup id 4.Effective group id 5.Real user id 6.Effective user id Enter the choice

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

6 The effective user id is 534 Do u wish to continue? (y/n)y ****************** The different IDs ****************** 1.Process id 2.Parent process id 3.Realgroup id 4.Effective group id 5.Real user id 6.Effective user id Enter the choice 5 The real user id is 534 Do u wish to continue? (y/n)n [m10mc09@linuxserver m10mc09]$

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:3 Date:

Demonstrate process creation using fork ().

#include<stdio.h> main() { int childpid; childpid=fork(); printf("\n childpid=%d",childpid); switch(childpid) { case -1: perror("can't fork"); exit(1); break; case 0: printf("\n child:child pid=%d,parent pid=%d \n",getpid(),getppid()); exit(0); break; default: printf("\n parent:child pid=%d,parent pid=%d \n",childpid,getpid()); exit(0); break; } }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

[m10mc22@linuxserver m10mc22]$ gcc pp17.c [m10mc22@linuxserver m10mc22]$ ./a.out childpid=0 child:child pid=5019,parent pid=5018 childpid=5019 parent:child pid=5019,parent pid=5018

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:4 Date:

Program to open,read,write using system call

#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<errno.h> #define BUF_SIZE 256 int main(int argc,char *argv[]) { int input_fd,output_fd; ssize_t bytes_in,bytes_out; char rec[BUF_SIZE]; if(argc!=3) { printf("Usage : cp file1 file2 \n"); return 1; } input_fd = open(argv[1],O_RDONLY); if(input_fd==-1) { perror(argv[2]); return 3; }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

output_fd = open(argv[2], O_WRONLY | O_CREAT,0666); if(output_fd==-1) { perror(argv[2]); return 3; } while((bytes_in=read(input_fd,&rec,BUF_SIZE))>0) { bytes_out=write(output_fd,&rec,bytes_in); if(bytes_out!=bytes_in) { perror("Fatal write error"); return 4; } } close(input_fd); close(output_fd); return 0; }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

[m10mc09@linuxserver m10mc09]$ cat > dee This is unix [m10mc09@linuxserver m10mc09]$ cat > deep Unix is goo to learn [m10mc09@linuxserver m10mc09]$ gcc -o systemcall.out systemcall.c [m10mc09@linuxserver m10mc09]$ ./systemcall.out dee deep dee is replaced with deep

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:5 Date:

Program to demonstrate process without locking.

#include<stdio.h> #define SEQFILE "seqno" #define MAXBUFF 100 main() { int fd,i,n,pid,seqno; char buff[MAXBUFF+1]; pid = getpid();

if((fd=open(SEQFILE,2))< 0 ) printf("Cant open %s",SEQFILE);

for(i=1;i<5;i++) { lseek(fd,0L,0); if((n=read(fd,buff,MAXBUFF))<=0) printf("\nread error\n"); buff[n]='\0';

n=sscanf(buff,"%d\n",&seqno); if((n=sscanf(buff, "%d\n" ,&seqno))!=1) printf("\n sscanf error\n");

printf("pid=%d,seq#=%d\n",pid,seqno);

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

seqno = seqno+1; sprintf(buff,"%03d\n",seqno); n=strlen(buff); lseek(fd,0L,0); if(write(fd,buff,n)!=n) printf("\nwrite error\n"); }}

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

[m10mc22@linuxserver m10mc22]$ cat > seqno 1 [m10mc22@linuxserver m10mc22]$ gcc pp18.c [m10mc22@linuxserver m10mc22]$ ./a.out pid=5027,seq#=1 pid=5027,seq#=2 pid=5027,seq#=3 pid=5027,seq#=4 [m10mc22@linuxserver m10mc22]$

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:6 Date:

Program to demonstrate File and Record Locking.

#include<stdio.h> #define SEQFILE "seqno" #define MAXBUFF 100 main () { int fd,i,n,pid,seqno; char buff[MAXBUFF+1]; pid = getpid(); if((fd=open(SEQFILE,2))< 0 ) printf("Cant open %s",SEQFILE); for(i=1;i<5;i++) { my_lock(fd); lseek(fd,0L,0); if((n=read(fd,buff,MAXBUFF))<=0) printf("\nread error\n"); buff[n]='\0'; n=sscanf(buff,"%d\n",&seqno); if((n=sscanf(buff, "%d\n" ,&seqno))!=1) printf("\n sscanf error\n"); printf("pid=%d,seq#=%d\n",pid,seqno); seqno = seqno+1; sprintf(buff,"%03d\n",seqno); n=strlen(buff);

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

lseek(fd,0L,0); if(write(fd,buff,n)!=n) printf("\nwrite error\n"); my_unlock(fd); } }

my_lock(fd) int fd; { return; } my_unlock(fd) int fd; { return; }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

[m10mc22@linuxserver m10mc22]$ gcc pp19.c [m10mc22@linuxserver m10mc22]$ ./a.out pid=5034,seq#=5 pid=5034,seq#=6 pid=5034,seq#=7 pid=5034,seq#=8 [m10mc22@linuxserver m10mc22]$

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:7 Date:

Program to implement IPC

#include<stdio.h> #include<unistd.h> #include<sys/types.h> int main(void) { int fd[2],nbytes; int childpid; char string[]="Hello 2nd MCA!/n"; char readbuffer[50]; pipe(fd); if((childpid = fork())== -1) { printf("fork"); exit(1); } if(childpid == 0) { close(fd[0]); write(fd[1],string,(strlen(string)+1)); exit(0); } else

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

{ close(fd[1]); nbytes=read(fd[0],readbuffer,sizeof(readbuffer)); printf("Received string: %s", readbuffer); } return(0); }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

[m10mc03@linuxserver dir1]$ gcc -o interpgm.out interprocess.c [m10mc03@linuxserver dir1]$ ./interpgm.out Received string: Hello 2nd MCA!/n[m10mc03@linuxserver dir1]$

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:8 Date:

Program to implement Pipes.

#include<stdio.h> main() { int pipefd[2],n; char buff[100]; if(pipe(pipefd)<0) printf("\nPipe error\n"); printf("read fd= %d,write fd= %d\n",pipefd[0],pipefd[1]); if(write(pipefd[1],"hello world\n",12)!=12) printf("\nwrite error\n"); if((n= read(pipefd[0],buff,sizeof(buff)))<=0) printf("\nRead error\n"); write(1,buff,n); exit(0); }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT
[m10mc22@linuxserver m10mc22]$ gcc pp16.c [m10mc22@linuxserver m10mc22]$ ./a.out read fd= 3,write fd= 4 hello world

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Pgm:9 Date:

Demonstrate cat command simulation

#include<unistd.h> #include<sys/types.h> #include<stdlib.h> #include<stdio.h> main(int arg,char *arr[]) { FILE *fp; char ch; if(arg!=3) { printf("Argument missing ! press key to exit"); exit(1); } fp=fopen(arr[2],"r"); if(fp==NULL) { printf("Cannot open source file!press key to exit"); exit(1); } while(1) {

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

ch=fgetc(fp); if(ch==EOF) break; printf("%c",ch); } fclose(fp); }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

OUTPUT

[m10mc03@linuxserver dir1]$ cat>text.txt hello this is pooh [m10mc03@linuxserver dir1]$ gcc -o catout.c catcmd.c [m10mc03@linuxserver dir1]$ ./catout.c text.txt Argument missing ! press key to exit[m10mc03@linuxserver dir1]$ ./catout.c text.

[m10mc03@linuxserver dir1]$ ./catout.c catcmd.c text.txt hello this is pooh [m10mc03@linuxserver dir1]$ ./catout.c text.txt

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Prg.No: 15 Date //IPC_msgq_send.c

Program to demonstrate Message Queues.

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXSIZE void die(char *s) { perror(s); exit(1); } struct msgbuf { long mtype; char }; main() { int msqid; int msgflg = IPC_CREAT | 0666; key_t key; struct msgbuf sbuf; size_t buflen; key = 1234; if ((msqid = msgget(key, msgflg )) < 0) //Get the message queue ID for the given key die("msgget"); //Message Type mtext[MAXSIZE]; 128

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

sbuf.mtype = 1; printf("Enter a message to add to message queue : "); scanf("%[^\n]",sbuf.mtext); getchar(); buflen = strlen(sbuf.mtext) + 1 ; if (msgsnd(msqid, &sbuf, buflen, IPC_NOWAIT) < 0) { printf ("%d, %ld, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buflen); die("msgsnd"); } else printf("Message Sent\n"); exit(0); } //IPC_msgq_rcv.c

#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #define MAXSIZE 128

void die(char *s) { perror(s); exit(1); }

typedef struct msgbuf {

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

long mtype; char }; mtext[MAXSIZE];

main() { int msqid; key_t key; struct msgbuf rcvbuffer; key = 1234; if ((msqid = msgget(key, 0666)) < 0) die("msgget()"); //Receive an answer of message type 1. if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0) die("msgrcv"); printf("%s\n", rcvbuffer.mtext); exit(0); }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Output:

(Server Prompt) [m10mc08@linuxserver m10mc08]$ gcc -o ser.out ser.c [m10mc08@linuxserver m10mc08]$ ./ser.out Enter a message to add to message queue : hello unix programming Message Sent [m10mc08@linuxserver m10mc08]$

(Client Prompt) [m10mc08@linuxserver m10mc08]$ gcc -o clt.out clt.c clt.c:18: warning: useless keyword or type name in empty declaration [m10mc08@linuxserver m10mc08]$ ./clt.out hello unix programming [m10mc08@linuxserver m10mc08]$

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Prg.No: 16

Program to demonstrate FIFO.

Date:

(Reciver)

#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #define FIFO_NAME "american_maid"

int main(void) { char s[300]; int num, fd; mknod(FIFO_NAME, S_IFIFO | 0666, 0); printf("waiting for writers...\n"); fd = open(FIFO_NAME, O_RDONLY); printf("got a writer\n"); do { if ((num = read(fd, s, 300)) == -1) perror("read"); else

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

{ s[num] = '\0'; printf("tick: read %d bytes: \"%s\"\n", num, s); } } while (num > 0);

return 0; }

(Sender) #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h>

#define FIFO_NAME "american_maid"

int main(void) { char s[300]; int num, fd;

mknod(FIFO_NAME, S_IFIFO | 0666, 0);

printf("waiting for readers...\n"); fd = open(FIFO_NAME, O_WRONLY); printf("got a reader--type some stuff\n");

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

while (gets(s), !feof(stdin)) { if ((num = write(fd, s, strlen(s))) == -1) //perror("write"); printf ("\n Writing"); else printf("speak: wrote %d bytes\n", num);

return 0; }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Output:

[m10mc08@linuxserver m10mc08]$ gcc -o fifosend.out fifosend.c [m10mc08@linuxserver m10mc08]$ ./fifosend.out waiting for readers... got a reader--type some stuff hello

[m10mc08@linuxserver m10mc08]$ gcc -o fiforec.out fiforec.c [m10mc08@linuxserver m10mc08]$ ./fiforec.out waiting for writers... got a writer hello

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Prg.No: 17

Program to demonstrate TCPClient/TCPServer.

Date:

/* tcpclient.c */

#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> int main()

int sock, bytes_recieved; char send_data[1024],recv_data[1024]; struct hostent *host; struct sockaddr_in server_addr;

host = gethostbyname("127.0.0.1");

if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

perror("Socket"); exit(1); }

server_addr.sin_family = AF_INET; server_addr.sin_port = htons(5000); server_addr.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(server_addr.sin_zero),8);

if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { perror("Connect"); exit(1); }

while(1) {

bytes_recieved=recv(sock,recv_data,1024,0); recv_data[bytes_recieved] = '\0';

if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0) { close(sock); break; }

else printf("\nRecieved data = %s " , recv_data);

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

printf("\nSEND (q or Q to quit) : "); gets(send_data);

if (strcmp(send_data , "q") != 0 && strcmp(send_data , "Q") != 0) send(sock,send_data,strlen(send_data), 0);

else { send(sock,send_data,strlen(send_data), 0); close(sock); break; }

} return 0; }

/* tcpserver.c */

#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> int main() { int sock, connected, bytes_recieved , true = 1;

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

char send_data [1024] , recv_data[1024]; struct sockaddr_in server_addr,client_addr; int sin_size; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket"); exit(1); }

if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == -1) { perror("Setsockopt"); exit(1); }

server_addr.sin_family = AF_INET; server_addr.sin_port = htons(5000); server_addr.sin_addr.s_addr = INADDR_ANY; bzero(&(server_addr.sin_zero),8);

if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { perror("Unable to bind"); exit(1); }

if (listen(sock, 5) == -1) { perror("Listen"); exit(1); }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

printf("\nTCPServer Waiting for client on port 5000"); fflush(stdout);

while(1) { sin_size = sizeof(struct sockaddr_in); connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size); printf("\n I got a connection from (%s , %d)", inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); while (1) { printf("\n SEND (q or Q to quit) : "); gets(send_data);

if (strcmp(send_data , "q") == 0 || strcmp(send_data , "Q") == 0) { send(connected, send_data,strlen(send_data), 0); close(connected); break; }

else send(connected, send_data,strlen(send_data), 0);

bytes_recieved = recv(connected,recv_data,1024,0);

recv_data[bytes_recieved] = '\0';

if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0) { close(connected);

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

break; }

else printf("\n RECIEVED DATA = %s " , recv_data); fflush(stdout); } }

close(sock); return 0; }

Mount Carmel College, M C A

Page No:

Unix Programming Lab 2011

Output:

[m10mc08@linuxserver m10mc08]$ gcc -o tcpserver.out tcpserver.c [m10mc08@linuxserver m10mc08]$ ./tcpserver.out

TCPServer Waiting for client on port 5000 I got a connection from (127.0.0.1 , 51533) SEND (q or Q to quit) : hello unix world

RECIEVED DATA = unixprogramming

[m10mc08@linuxserver m10mc08]$ gcc -o tcpclient.out tcpclient.c [m10mc08@linuxserver m10mc08]$ ./tcpclient.out

Recieved data = hello SEND (q or Q to quit) : unixprogramming

Recieved data = unix SEND (q or Q to quit) :q

Mount Carmel College, M C A

Page No:

Das könnte Ihnen auch gefallen