Shell Script

September 1, 2017 | Author: Neo Dragon | Category: Command Line Interface, Computer File, Unix, Areas Of Computer Science, Computer Data
Share Embed Donate


Short Description

UNIX PROGRAMMING – LAB PROGRAMS Write a shell script for sorting, searching, insertion, deletion and displaying of eleme...

Description

UNIX PROGRAMMING – LAB PROGRAMS Write a shell script for sorting, searching, insertion, deletion and displaying of elements in a list. Program #!/bin/sh clear i=1 echo Enter the size of array : read n echo Enter $n elements : while [ $i -le $n ] do read a[$i] i=`expr $i + 1` done while true do i=1 j=1 clear echo 1. Sort echo 2. Search echo 3. Insert echo 4. Delete echo 5. Display echo 6. Exit echo Enter your choice : read ch case $ch in 1) while [ $i -le $n ] do j=1 while [ $j -le $n ] do if [ ${a[$i]} -lt ${a[$j]} ] then t=${a[$i]} a[$i]=${a[$j]} a[$j]=$t fi j=`expr $j + 1` done i=`expr $i + 1` done ;; 2) echo Enter the element to search : flag=0 read e while [ $i -le $n ] do if [ $e -eq ${a[$i]} ] then flag=1

Prepared By : BILAL AHMED SHAIK

Page No : 1

UNIX PROGRAMMING – LAB PROGRAMS break else flag=0 fi i=`expr $i + 1` done if [ $flag -eq 0 ] then echo The element not found else echo The element found fi ;; 3) echo Enter the element to insert read e echo Enter the position to insert read pos if [ $pos -gt `expr $n + 1` ] then echo Wrong Position fi if [ $pos -eq `expr $n + 1` ] then n=`expr $n + 1` a[$n]=$e else n=`expr $n + 1` p=`expr $n - $pos` n1=$n while [ $p -gt 0 ] do n2=`expr $n1 - 1` a[$n1]=${a[$n2]} n1=`expr $n1 - 1` p=`expr $p - 1` done a[$pos]=$e fi ;; 4) echo Enter the position to be deleted read pos if [ $pos -gt $n ] then echo Wrong Position else p=`expr $n - $pos` while [ $p -ge 0 ] do po=`expr $pos + 1` a[$pos]=${a[$po]} pos=`expr $pos + 1` p=`expr $p - 1` done

Prepared By : BILAL AHMED SHAIK

Page No : 2

UNIX PROGRAMMING – LAB PROGRAMS n=`expr $n - 1` fi ;; 5) i=1 while [ $i -le $n ] do echo ${a[$i]} i=`expr $i + 1` done ;; 6) exit ;; esac read key done

OUTPUT Enter the size of array : 5 Enter 5 elements : 65 34 27 12 53 1.Sort 2.Search 3.Insert 4.Delete 5.Display 6.Exit Enter your choice :

1

1.Sort 2.Search 3.Insert 4.Delete 5.Display 6.Exit Enter your choice :

5

12 27 34 53 65 Write a program to display the 'Good Morning', 'Good After Noon', 'Good Evening' and 'Good Night' depending on the users log on time PROGRAM

Prepared By : BILAL AHMED SHAIK

Page No : 3

UNIX PROGRAMMING – LAB PROGRAMS #!/bin/sh clear t=`date | awk '{ print $4 }' | awk -F: '{ print $1 }'` if [ $t -le 12 ] then echo Good Morning, Now the time is `date +%H:%M:%S` elif [ $t -ge 12 -a $t -lt 15 ] then echo Good After Noon, Now the time is `date +%H:%M:%S` elif [ $t -ge 15 -a $t -lt 19 ] then echo Good Evening, Now the time is `date +%H:%M:%S` else echo Good Night, Now the time is `date +%H:%M:%S` fi (or) #!/bin/sh Clear T=`date + %k` If[ $t –ge 0 –a $t –le 12 ] echo “Good Morning, `logname`” elif[ $t –ge 12 –a $t –le 14 ] echo “Good Afternoon, `logname`” elif[ $t –ge 14 –a $t –le 18 ] echo “Good Evening, `logname`” else echo “Good night, `logname`” Done OUTPUT Good Evening, Now the time is 16:00:21 Write a shell script which work similar to the 'WC' command. This script can receive the option -w, -c, -l to indicate whether number of words / characters / lines. PROGRAM #!/bin/sh clear echo "Enter any Filename to count no of characters, words and lines" read fname while true do clear echo " 1. Characters 2. Words 3. Lines 4. exit" echo Enter your choice read ch if [ $ch -eq 1 ] then echo Total No of Characters ;wc -c $fname elif [ $ch -eq 2 ] then echo Total No of Words ;wc -w $fname

Prepared By : BILAL AHMED SHAIK

Page No : 4

UNIX PROGRAMMING – LAB PROGRAMS elif [ $ch -eq 3 ] then echo Total No of Lines ;wc -l $fname elif [ $ch -eq 4 ] then break fi sleep 5 done OUTPUT Enter any Filename to count no of characters, words and lines sample Menu 1. characters 2. words 3. lines 4. exit Enter your choice 1 Total No of Characters 200 Write a program to print prime numbers between X and Y. PROGRAM #!/bin/sh clear echo "ENTER X AND Y" read x read y echo Prime Numbers between $x and $y are while [ $x -le $y ] do r=0 i=2 count=0 while [ $i -le `expr $x / 2` ] do r=`expr $x % $i` if [ $r -eq 0 ] then count=1 break fi i=`expr $i + 1` done if [ $count -eq 0 ] then echo $x fi x=`expr $x + 1` done OUTPUT ENTER X AND Y

Prepared By : BILAL AHMED SHAIK

Page No : 5

UNIX PROGRAMMING – LAB PROGRAMS 1 10 Prime Numbers between 1 and 10 are 1 2 3 5 7 Write a shell script which deletes all lines containing the word 'UNIX' in the files supplied as arguments to the shell script PROGRAM #!/bin/sh clear for file do grep -v unix $file > temp cp temp $file rm temp done OUTPUT First create the files with the name samp1 and samp2 at shell command prompt $>cat > samp1 hello this is unix $> cat > samp2 C java

hello this is C unix

.net

Now execute the shell script by typing sh shell script filename samp1 samp2 at shell command prompt. After executing see the contents of the files samp1 and samp2. You will observe that the lines containing the word unix will be removed. $>cat samp1 hello this is C $> cat samp2 C

java

.net

Write a shell script which displays a list of all files in the current working directory to which we have read, write and execute permissions PROGRAM #!/bin/sh clear echo "The files which are having read, write and execute permissions are" for i in * do if [ -r $i -a -w $i -a -x $i ] then echo $i fi done

Prepared By : BILAL AHMED SHAIK

Page No : 6

UNIX PROGRAMMING – LAB PROGRAMS OUTPUT First give read, write and execute permissions for some files using chmod and then execute the shell script to get the output The files which are having read, write and execute permissions are a b Write a menu driven program which has following options Contents of /etc/passwd List of users who have currently logged in Present working directory Exit etc... PROGRAM #!/bin/sh clear while true do clear echo "1. FILES IN /ETC/PASSWD" echo "2. LIST OF USERS CURRENTLY LOGGEDIN" echo "3. PRESENT WORKING DIRECTORY" echo "4. EXIT" echo "ENTER YOUR CHOICE" read ch if [ $ch -eq 1 ] then clear cat /etc/passwd echo "PRESS ANY KEY TO CONTINUE...." read i elif [ $ch -eq 2 ] then clear who echo "PRESS ANY KEY TO CONTINUE...." read i elif [ $ch -eq 3 ] then clear pwd echo "PRESS ANY KEY TO CONTINUE...." read i else break fi done OUTPUT 1. FILES IN /ETC/PASSWD 2. LIST OF USERS CURRENTLY LOGGEDIN 3. PRESENT WORKING DIRECTORY 4. EXIT

Prepared By : BILAL AHMED SHAIK

Page No : 7

UNIX PROGRAMMING – LAB PROGRAMS ENTER U R CHOICE 2 root :0 2006-11-17 10:36 root pts/2 2006-11-17 13:39 (:0.0) PRESS ANY KEY TO CONTINUE....

Write a shell script for renaming each file in the directory such that it will have current shell id as and extension. The shell script should ensure that the directories do not get renamed. PROGRAM #!/bin/sh clear for i in * do if [ -f $i ] then echo ;mv $i $i.$$ fi done OUTPUT First create some files with the name a b c d and directories x y z in a sub folder(eg sample) of current working directory. Then execute the shell script by passing the sub folder(sample) as an argument to the shell script. After execution you will find all the files present in the sub folder will get extension of the current shell id. $ sample>ls a.19647 b.19647 c.19647 d.19647 x y z

Prepared By : BILAL AHMED SHAIK

Page No : 8

UNIX PROGRAMMING – LAB PROGRAMS Write a shell script that takes a command – line argument and reports on whether it is directory, a file, or something else. PROGRAM #!/bin/sh clear if [ $# -ne 1 ] then echo "This script requires a filename as an argument" echo "Usage : script_name " exit 1 fi ls $1 1> /dev/null 2>1 if [ $? -ne 0 ] then echo "$1 File does not exist" exit 2 fi if [ -f $1 ] then echo "$1 is a Regular File" elif [ -d $1 ] then echo "$1 is a Directory File" else echo "$1 is not a Regular or Directory file" fi Write a shell script that determines the period for which a specified user is working on the system. PROGRAM #!/bin/bash clear echo -e "Enter Username : \c" read uname who | grep $uname > /dev/null if [ $? -eq 0 ] then lh=`who | grep $uname | cut -c 36-37` lm=`who | grep $uname | cut -c 39-40` ch=`date | cut -c 12-13` cm=`date | cut -c 15-16` ot=`expr $lh \* 60 \* 60 + $lm \* 60` ct=`expr $ch \* 60 \* 60 + $cm \* 60` td=`expr $ct - $ot` tm=`expr $td / 60` hd=`expr $tm / 60` md=`expr $tm % 60` echo "The $uname user logged in for past $hd hours $md minutes" else echo "The $uname user not logged in" fi

Prepared By : BILAL AHMED SHAIK

Page No : 9

UNIX PROGRAMMING – LAB PROGRAMS Write a shell script to perform the following string operations. To extract a sub string from a given string. To find the length of a given string. PROGRAM #!/bin/sh clear echo "Menu" echo "1. To extract a substring from a given string." echo "2. To Find the length of the given string." echo -e "Enter your choice... : \c" read ch echo -e "Enter any string : \c" read st case $ch in 1) echo -e "Enter substring : \c" read sst echo $st | grep $sst > /dev/null if [ $? -eq 0 ] then echo "The substring '$sst' found in the given string" else echo "'The substring $sst' not found in the given string" fi;; 2) l=`echo $st | wc -c` l=`expr $l - 1` echo "The length of the given string '$st' is $l";; *) echo "Invalid choice... Try Again!";; esac Develop an interactive script that asks for a word and file name and then tells how many times that word occurred in the file. PROGRAM #!/bin/sh clear echo –e "Enter any Filename : \c" read fname if [ ! -f $fname ] then echo "Enter only regular filenames" exit 1 fi echo –e "Enter word to search in $fname file : \c" read sword echo "The search word $sword is repeated for `grep -c $sword $fname` times in the given file $fname"

Prepared By : BILAL AHMED SHAIK

Page No : 10

UNIX PROGRAMMING – LAB PROGRAMS Write a shell script which receives two files names as arguments. It should check whether the two file contents are same or not. If they are same then second file should be deleted. PROGRAM #!/bin/sh clear if [ $# -ne 2 ] then echo "This script requires two filenames as arguments" echo "Usage : script_name " exit 1 fi if [ -d $1 -o -d $2 ] then echo "Directory name is given as an argument, check it..." exit 2 fi ls $1 $2 1> /dev/null 2>1 if [ $? != 0 ] then echo "Provided File does not exist" exit 3 fi cmp $1 $2 > /dev/null if [ $? == 0 ] then rm -f $2 echo "The two files $1 and $2 are identical, hence $2 file is deleted" else echo "The two files $1 and $2 are not identical" fi Write a shell script that takes a login name as command – line argument and reports when that person logs in PROGRAM #!/bin/sh clear if [ $# -ne 1 ] then echo "This script requires one user name as an argument" echo "Usage : script_name " exit 1 fi who | grep $1 > /dev/null if [ $? -eq 0 ] then echo "The $1 user logged on to the system on `who | grep $1 | cut -c 36-40`" else echo "The $1 user not logged in yet" fi

Prepared By : BILAL AHMED SHAIK

Page No : 11

UNIX PROGRAMMING – LAB PROGRAMS Write an interactive file handling shell program. Let it offer the user the choice of copying, removing, renaming or linking files. Once the use has made a choice, have the program ask the user for necessary information, such as the file name, new name and so on. PROGRAM #!/bin/sh clear echo "1.FILE COPYING" echo "2.FILE RENAMING" echo "3.FILE REMOVING" echo "4.FILE LINKING" echo -e "ENTER YOUR CHOICE : \c" read choice case $choice in 1) echo -e "Enter the source filename : \c" read sfile if [ ! -f $sfile ] then echo "Source File does not exist... Try again!" exit 1 fi echo -e "Enter the target filename : \c" read tfile cp $sfile $tfile 1> /dev/null 2>1 if [ $? -eq 0 ] then echo "File copied successfully" else echo "Problem with the destination filename" fi;; 2) echo -e "Enter the source filename : \c" read sfile if [ ! -f $sfile ] then echo "Source File does not exist... Try again!" exit 1 fi echo -e "Enter the new filename for the source file : \c" read tfile mv $sfile $tfile 1> /dev/null 2>1 if [ $? -eq 0 ] then echo "File renamed succeessfully" else echo "Problem with the destination filename" fi;; 3) echo -e "Enter the source filename : \c" read sfile if [ ! -f $sfile ] then echo "Source File does not exist... Try again!" exit 1 fi rm -f $sfile 1> /dev/null 2>1 if [ $? -eq 0 ]

Prepared By : BILAL AHMED SHAIK

Page No : 12

UNIX PROGRAMMING – LAB PROGRAMS then echo "File removed successfully" else 4)

*)

echo "Error while reomoving file" fi;; echo -e "Enter the source filename : \c" read sfile if [ ! -f $sfile ] then echo "Source File does not exist... Try again!" exit 1 fi echo -e "Enter the link name for the source file : \c" read tfile link $sfile $tfile 1> /dev/null 2>1 if [ $? -eq 0 ] then echo "File linked successfully" else echo "Error while linking file" fi;; echo "Invalid choice... Try again!";;

esac Write a shell script that accepts two integers as its arguments and computes the value of first number raised to the power of the second number PROGRAM #!/bin/sh clear if [ $# -ne 2 ] then clear echo "This script requires two integers as arguments" echo "Usage : script_name " exit 1 fi i=1 result=1 while [ $i -le $2 ] do result=`expr $result \* $1` i=`expr $i + 1` done echo "$1 raised to the power of $2 is $result"

Prepared By : BILAL AHMED SHAIK

Page No : 13

UNIX PROGRAMMING – LAB PROGRAMS Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it. PROGRAM #!/bin/sh clear if [ $# -lt 1 ] then echo "This script requires atleast one filename as an argument" echo "Usage : script_name " exit 1 fi i=1 n=$# echo –e "Enter Word to search : \c" read swrd while [ $i -le $n ] do if [ -f $(eval echo \$$i) ] then echo "Deleting lines that contains the word $swrd from $(eval echo \$$i) file" grep -v $swrd $(eval echo \$$i) > tmp ; mv tmp $(eval echo \$$i) else echo "$(eval echo \$$i) is not a file or it does not exist" fi i=`expr $i + 1` done OUTPUT

Prepared By : BILAL AHMED SHAIK

Page No : 14

UNIX PROGRAMMING – LAB PROGRAMS Write a shell script that accepts a file name starting and ending line numbers as arguments and displays all the lines between the given line numbers. PROGRAM #!/bin/sh clear if [ $# -ne 3 ] then clear echo "This script requires a filename, starting and ending line numbers as an argument" echo "Usage : script_name " exit 1 fi if [ $2 -gt $3 ] then echo "Starting line number should be less than ending line number" exit 2 fi ls $1 1> /dev/null 2>1 if [ $? -ne 0 ] then echo "$1 File does not exist" exit 3 fi if [ -f $1 ] then head -$3 $1 | tail +$2 else echo "$1 is not a Regular File" fi OUTPUT

Prepared By : BILAL AHMED SHAIK

Page No : 15

UNIX PROGRAMMING – LAB PROGRAMS Create two processes to run a for loop which adds numbers from 1 to n, say one process adds odd numbers and the other even. PROGRAM #include #include main() { int i,n,esum=0,osum=0,pid; printf("\n Enter N value : "); scanf("%d",&n); if((pid=fork())==0) { printf("\n Child Process is calculating the sum of even numbers between 1 to %d",n); for(i=1;i0) { printf("\n Parent Process is calculating the sum of odd numbers between 1 to %d",n); for(i=1;i0) { if(choice==1 && (ch >=65 && ch =97 && ch=97 && ch =65 && ch Cat > sample Hello Welcome to UNIX WORLD Then execute the program by giving the above file as source file and give a new filename for the target file $>./convert sample temp 1. convert capital letters into small 2. convert small letters into capital 3. convert small to capital and capital to small Enter your choice : 3 After execution see the contents of the temp file. $>Cat temp hELLO wELCOME TO unix world Write a program which takes a set of filenames along with the command line and print them based on their size in bytes either ascending or descending order PROGRAM #include #include #include #include int main(int argc,char **argv) { struct stat x; int i,j; size_t *filesize,t; char *tmp; if(argc==-1) { printf("usage:%s .....",argv); exit(1); } filesize=(size_t *) malloc ((argc-1) * sizeof(size_t)); for(i=1;id_name); stat(name,&x); if(S_ISREG(x.st_mode)) no_of_files++; } size=(long *)malloc(no_of_files *sizeof(long)); ino=(long *)malloc(no_of_files *sizeof(long)); file=(char **)malloc(no_of_files *sizeof(char *)); rewinddir(d); while((dir=readdir(d))) { name=(char *)realloc(name,strlen(argv[1])+dir->d_reclen+2); sprintf(name,"%s/%s",argv[1],dir->d_name); stat(name,&x); if(S_ISREG(x.st_mode)) { size[i]=x.st_size; ino[i]=dir->d_ino; file[i]=dir->d_name; i++; } } for(i=0;i ln a y

$> ln c z

$> sample prog

$ ln b bb ....

Then come out from the subdirectory and execute the program $> ./countlinks

eg. $> ./countlinks samp

After executing it displays the files which r having more than one link in the following style ----------------------------------------------------------------------------------------Inode Files which r having more than one link size in bytes ---------------------------------------------------------------------------------------1867903 y a x 6 1867904 bb b bbb bbbb 12 1867905 z c 14 1867906 prog sample 0 --------------------------------------------------------------------------------------Write a program to demonstrating the use of exec family functions PROGRAM PRGEXEC.C #include #include char *env_init[]={"user=kiran", "PATH=/tmp", NULL}; char *argarray[]={"dispprg","myarg1","myarg2","myarg3","myarg4"}; main() { int pid; if( (pid=fork()) < 0 ) printf("\n Error while creating process"); else if(pid==0) { printf("\n -----------------------------------------------------------------"); printf("\n EXECL "); printf("\n------------------------------------------------------------------"); if( execl("/home/kiran/dispprg","dispprg","myarg1","myarg2",(char *) 0) < 0 ) printf("\n Error in Execl"); } if(waitpid(pid,NULL,0) < 0)

Prepared By : BILAL AHMED SHAIK

Page No : 21

UNIX PROGRAMMING – LAB PROGRAMS printf("\n wait error"); if( (pid=fork()) < 0 ) printf("\n Error while creating process"); else if(pid==0) { printf("\n -----------------------------------------------------------------"); printf("\n EXECLE "); printf("\n------------------------------------------------------------------"); if( execle("/home/kiran/dispprg","dispprg","myarg1","myarg2",(char *) 0, env_init) < 0 ) printf("\n Error in Execle"); } if(waitpid(pid,NULL,0) < 0) printf("\n wait error"); if( (pid=fork()) < 0 ) printf("\n error while creating process"); else if(pid==0) { printf("\n -----------------------------------------------------------------"); printf("\n EXECLP "); printf("\n------------------------------------------------------------------"); if(execlp("./dispprg","dispprg","only 1 arg", (char *) 0) < 0) printf("\n Error in Execlp"); } if(waitpid(pid,NULL,0) < 0) printf("\n wait error"); if( (pid=fork()) < 0 ) printf("\n error while creating process"); else if(pid==0) { printf("\n -----------------------------------------------------------------"); printf("\n EXECV "); printf("\n------------------------------------------------------------------"); if(execv("/home/kiran/dispprg",argarray) < 0) printf("\n Error in Execlp"); } if(waitpid(pid,NULL,0) < 0) printf("\n wait error"); if( (pid=fork()) < 0 ) printf("\n error while creating process"); else if(pid==0) { printf("\n -----------------------------------------------------------------"); printf("\n EXECVP "); printf("\n------------------------------------------------------------------"); if(execvp("./dispprg",argarray) < 0) printf("\n Error in Execlp"); } if(waitpid(pid,NULL,0) < 0) printf("\n wait error"); if( (pid=fork()) < 0 ) printf("\n error while creating process"); else if(pid==0) {

Prepared By : BILAL AHMED SHAIK

Page No : 22

UNIX PROGRAMMING – LAB PROGRAMS printf("\n -----------------------------------------------------------------"); printf("\n EXECL "); printf("\n------------------------------------------------------------------"); if(execve("/home/kiran/dispprg",argarray,env_init) < 0) printf("\n Error in Execlp"); } if(waitpid(pid,NULL,0) < 0) printf("\n wait error"); } DISPPRG.C #include main(int argc, char *argv[]) { int i; char **ptr; extern char **environ; printf("\n -------------------------- \n Printing Arguments \n --------------------------"); for(i=0;i ./shm_process2 abcdefghijklmnopqrstuvwxyz another process had red the data $> After executing the shm_process2 it will read the data which is placed by shm_process1 from the shared memory and writes * to it. Write a program demonstrating locking mechanisms while accessing shared files. PROGRAM #include #include #include #include #include int main(int argc, char *argv[]) { struct flock fl; int fd,ch; fl.l_whence=SEEK_SET; fl.l_start=0; fl.l_len=0; fl.l_pid=getpid(); if(argc!=2) {

Prepared By : BILAL AHMED SHAIK

Page No : 26

UNIX PROGRAMMING – LAB PROGRAMS printf("\n Usage : %s ",argv[0]); exit(0); } if((fd=open(argv[1],O_RDWR))==-1) { printf("\n Error while opening "); exit(1); } while(1) { printf("\n\n 1. Set Read Lock"); printf("\n 2. Set Write Lock"); printf("\n 3. Unset Read / Write Lock"); printf("\n 4. Exit"); printf("\n\n Enter your choice : "); scanf("%d",&ch); if(ch==1) { fl.l_type=F_RDLCK; if(fcntl(fd,F_SETLKW,&fl)==-1) { printf("\n Error in fcntl while seting Read Lock"); exit(2); } else printf("\n Locked for reading by PID %d ",getpid()); } else if(ch==2) { fl.l_type=F_WRLCK; if(fcntl(fd,F_SETLKW,&fl)==-1) { printf("\n Error in fcntl while seting Write Lock"); exit(3); } else printf("\n Locked for writing by PID %d ",getpid()); } else if(ch==3) { fl.l_type=F_UNLCK; if(fcntl(fd,F_SETLK,&fl)==-1) { printf("\n Error in fcntl while unseting Read / Write Lock"); exit(4); } else printf("\n Read / Write Lock Unseted for PID %d ",getpid()); } else if(ch==4) break; else

Prepared By : BILAL AHMED SHAIK

Page No : 27

UNIX PROGRAMMING – LAB PROGRAMS printf("\n Enter choice between 1 to 4 only"); } } OUTPUT After compiling execute the program in two terminals. Here all the processes can set read lock. But only one process can set the write lock. Process 1 Process 2 1. Set Read Lock 2. Set Write Lock 3. Unset Read / Write Lock 4. Exit

1. Set Read Lock 2. Set Write Lock 3. Unset Read / Write Lock 4. Exit

Enter your choice : 1 Enter your choice : 1 Locked for reading by PID 3323 Locked for reading by PID 3326 1. Set Read Lock 2. Set Write Lock 3. Unset Read / Write Lock 4. Exit

1. Set Read Lock 2. Set Write Lock 3. Unset Read / Write Lock 4. Exit

Enter your choice : 2 Enter your choice : 3 Locked for writing by PID 3323 Read / Write Lock Unseted for PID 3326 1. Set Read Lock 2. Set Write Lock 3. Unset Read / Write Lock 4. Exit

1. Set Read Lock 2. Set Write Lock 3. Unset Read / Write Lock 4. Exit

Enter your choice : Enter your choice :

Write a program demonstrating semaphore operation on a shared file for reading but not writing PROGRAM #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { struct flock fl; int fd, ch, semid, sc; struct sembuf sem_op; fl.l_whence=SEEK_SET;

Prepared By : BILAL AHMED SHAIK

Page No : 28

UNIX PROGRAMMING – LAB PROGRAMS fl.l_start=0; fl.l_len=0; fl.l_pid=getpid(); sem_op.sem_num=0; sem_op.sem_flg=0; if(argc!=2) { printf("\n Usage : %s ",argv[0]); exit(0); } if((semid=semget(998,1,IPC_CREAT | 0666))==-1) { printf("\n Error in semophore"); exit(1); } if(semctl(semid,0,GETVAL,1)>0) { if((sc=semctl(semid,0,SETVAL,1))==-1) { printf("\n Error in semctl while initilizing semophore"); exit(2); } } if((fd=open(argv[1],O_RDWR))==-1) { printf("\n Error while opening "); exit(3); } while(1) { printf("\n\n 1. Set Read Lock"); printf("\n 2. Set Write Lock"); printf("\n 3. Unset Read / Write Lock"); printf("\n 4. Exit"); printf("\n\n Enter your choice : "); scanf("%d",&ch); if(ch==1) { fl.l_type=F_RDLCK; sem_op.sem_op=-1; semop(semid,&sem_op,1); if(fcntl(fd,F_SETLKW,&fl)==-1) { printf("\n Error in fcntl while seting Read Lock"); exit(4); } else printf("\n Locked for reading by PID %d",getpid()); } else if(ch==2) { fl.l_type=F_WRLCK; if(fcntl(fd,F_SETLKW,&fl)==-1) { printf("\n Error in fcntl while seting Write Lock"); exit(5);

Prepared By : BILAL AHMED SHAIK

Page No : 29

UNIX PROGRAMMING – LAB PROGRAMS } else printf("\n Locked for writing by PID %d",getpid()); } else if(ch==3) { fl.l_type=F_UNLCK; if(semctl(semid,0,GETVAL,1)0) { write(dstfd,buff,nbytes); } close(dstfd); close(srcfd); printf("\n File Copied Sucessfully \n\n"); } OUTPUT

Write a c program that simulates ls command (Use system calls / directory API) PROGRAM #include #include #include #include #include int main() { size_t sz; char pathname[100]; struct dirent *DirectoryEntry; DIR *DirectoryStream; int i=0; getcwd(pathname,sz); printf("%s\n",pathname); if((DirectoryStream=opendir(pathname))==NULL) { printf("\n Error while opening directory"); exit(1); } while((DirectoryEntry=readdir(DirectoryStream))) { printf("\n %s",DirectoryEntry->d_name); } closedir(DirectoryStream); } OUTPUT

/* tcpserver.c */ #include #include #include #include #include #include #include #include #include int main() { int sock, connected, bytes_recieved , true = 1; 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); } 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); break; } else printf("\n RECIEVED DATA = %s " , recv_data); fflush(stdout); } } close(sock); return 0; } /* tcpclient.c */ #include #include #include #include #include #include #include #include #include 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) { 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); 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; }

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF