• No results found

Shell Script

N/A
N/A
Protected

Academic year: 2021

Share "Shell Script"

Copied!
38
0
0

Loading.... (view fulltext now)

Full text

(1)

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

(2)

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

(3)

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

(4)

#!/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

(5)

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`

(6)

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 hello this is C $> cat > samp2

C java 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

(7)

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

(8)

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

(9)

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 <filename>"

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

(10)

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

(11)

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 <file_name1> <file_name2>" 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 <user_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

(12)

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 ]

(13)

then

echo "File removed successfully" else

echo "Error while reomoving file" fi;;

4) 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 <n1> <n2>"

exit 1 fi i=1 result=1 while [ $i -le $2 ] do result=`expr $result \* $1` i=`expr $i + 1` done

(14)

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 <file_list>"

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

(15)

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 <filename> <starting line number> <ending line number>" 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

(16)

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<stdio.h> #include<stdlib.h> 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;i<=n;i++) { if((i%2)==0)

esum=esum+i; }

printf("\n Even numbers sum is %d",esum); exit(0);

}

else if(pid>0) {

printf("\n Parent Process is calculating the sum of odd numbers between 1 to %d",n);

for(i=1;i<=n;i++)

{ if((i%2)!=0)

osum=osum+i;

}

printf("\n Odd numbers sum is %d",osum); }

exit(1); }

OUTPUT

Enter N value : 10

Child Process is calculating the sum of even numbers between 1 to 10 Even numbers sum is 30

Parent Process is calculating the sum of odd numbers between 1 to 10 Odd numbers sum is 25

Write a program which reads a source filename and destination filename using command line arguments and then converts into specified format.

1. convert capital letters into small 2. convert small letters into capital

3. convert small to capital and capital to small PROGRAM

(17)

#include<sys/stat.h> #include<sys/fcntl.h> #include<stdlib.h>

int main(int argc,char *argv[]) { char *file_path_from; char *file_path_to; int f_from; int f_to; char ch; int choice;

if ( argc != 3 || !argv[1] || !argv[2] ) {

fprintf(stderr,"usage : %s <source file path> <target file path>\n",argv[0]); exit(1);

}

printf("\n 1. Convert capital letters into small"); printf("\n 2. Convert small letters into capital");

printf("\n 3. Convert small to capital and capital to small"); printf("\n Enter your choice : ");

scanf("%d",&choice); file_path_from=argv[1]; file_path_to=argv[2]; f_from=open(file_path_from,O_RDONLY); if(f_from==-1) {

perror("Cannot open source file"); exit(1);

}

f_to=open(file_path_to,O_RDWR|O_CREAT,0700); if(f_to==-1)

{

perror("Cannot open target file"); exit(1);

}

while(read(f_from,&ch,1)>0) {

if(choice==1 && (ch >=65 && ch <=90)) ch=ch+32;

else if(choice==2 && (ch >=97 && ch<=122)) ch=ch-32;

else if(choice==3)

{ if(ch>=97 && ch <=122) ch=ch-32;

else if(ch >=65 && ch <=90) ch=ch+32;

} write(f_to,&ch,1);

}

if(close(f_from)==-1)

perror("error while closing the source file"); if(close(f_to)==-1)

(18)

First Create a file with the name sample and type some text in it. $>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<sys/stat.h> #include<stdlib.h> #include<stdio.h> #include<sys/types.h> int main(int argc,char **argv) { struct stat x; int i,j; size_t *filesize,t; char *tmp; if(argc==-1) { printf("usage:%s <filename1><filename2>...",argv); exit(1); }

filesize=(size_t *) malloc ((argc-1) * sizeof(size_t)); for(i=1;i<argc;i++)

{

if(stat(argv[i],&x)<0) {

printf("error in getting status"); exit(2);

}

filesize[i-1]=x.st_size; }

(19)

{ for(j=0;j<argc-i-2;j++) { if(filesize[j]>filesize[j+1]) { t=filesize[j]; filesize[j]=filesize[j+1]; filesize[j+1]=t; tmp=argv[j+1]; argv[j+1]=argv[j+2]; argv[j+2]=tmp; } } } for(i=0;i<argc-1;i++) printf("\n %s-%d",argv[i+1],filesize[i]); return 0; } OUTPUT

First create some files a b c d with some contents. Type ls -l to display the files in long format. -rwxr-xr-x 1 root root 5377 Nov 17 18:07 a

-rw-r--r-- 1 root root 741 Nov 17 11:37 b -rw-r--r-- 1 root root 1495 Nov 17 11:39 c -rw-r--r-- 1 root root 3511 Nov 17 15:06 d $>sortfiles a b c d

After executing the files will be displayed in the following order b-741

c-1495 d-3511 a-5377

Write a program which takes directory name along the command line and displays names of the files which are having more than 1 link.

PROGRAM #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<dirent.h> #include<string.h> #include<sys/types.h> #include<sys/stat.h>

int main(int argc,char **argv) {

(20)

char *name=NULL,**file; if(argc==1)

{

printf("\n usage : %s <directoryname>",argv[0]); exit(1);

}

if((d=opendir(argv[1]))==NULL) {

printf("\n error in opening directory"); exit(2); } 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)) 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<no_of_files-1;i++) { for(j=0;j<no_of_files-i-1;j++) { if(ino[j]>ino[j+1]) {

long t; t=ino[j]; ino[j]=ino[j+1]; ino[j+1]=t;

t=size[j]; size[j]=size[j+1]; size[j+1]=t;

name=file[j]; file[j]=file[j+1]; file[j+1]=name; }

} }

l=0;

printf("\n ---"); printf("\n Inode \t Files which r having more than one link \t size in bytes");

printf("\n ---"); for(i=0;i<no_of_files;i++)

{ if(ino[i]==l || ino[i]==ino[i+1]) { if(ino[i]!=l)

(21)

{ l=ino[i]; printf("\n %ld \t",l); } printf(" %s ",file[i]); if(ino[i]!=ino[i+1]) printf("\t\t\t\t\t %ld ",size[i]); } } printf("\n --- \n"); exit(0); } OUTPUT

First create some files with the names a b c d sample in any subdirectory of current working directory. Then enter into subdirectory and use ln command at shell prompt to provide links for the files

$> ln a x $> ln a y $> ln c z $> sample prog $ ln b bb .... Then come out from the subdirectory and execute the program

$> ./countlinks <subdirectory name> 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<stdio.h> #include<unistd.h> 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---");

(22)

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)

(23)

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<stdio.h>

main(int argc, char *argv[]) {

int i; char **ptr;

extern char **environ;

printf("\n --- \n Printing Arguments \n ---");

for(i=0;i<argc;i++)

printf("\n argv[%d]: %s",i,argv[i]); printf("\n --- \n printing Environment \n ---"); for(ptr=environ;*ptr!=0;ptr++) printf("\n %s",*ptr); } OUTPUT EXECLE Printing Arguments argv[0]: dispprg argv[1]: myarg1 argv[2]: myarg2 Printing Environment user=kiran PATH=/tmp ---EXECLP Printing Arguments

(24)

Printing Environment SSH_AGENT_PID=4236 HOSTNAME=localhost.localdomain DESKTOP_STARTUP_ID= SHELL=/bin/bash TERM=xterm HISTSIZE=1000 GTK_RC_FILES=/etc/gtk/gtkrc:/root/.gtkrc-1.2-gnome2 ... EXECVP ---Printing Arguments argv[0]: dispprg argv[1]: myarg1 argv[2]: myarg2 argv[3]: myarg3 argv[4]: myarg4 ---Printing Environment SSH_AGENT_PID=4236 HOSTNAME=localhost.localdomain DESKTOP_STARTUP_ID= SHELL=/bin/bash TERM=xterm HISTSIZE=1000

Write a program demonstrating the working of simple signal handler that caches either of the user defined signals and prints the signal number.

PROGRAM #include<stdio.h> #include<signal.h> #include<stdlib.h>

void catch_mysignal(int signo) {

printf("SEGMENTATION PROBLEM \n SIGNAL NO IS : %d",signo); exit(1); } main() { int a=10,b=0,c; signal(SIGFPE,catch_mysignal); c=a/b; } OUTPUT SEGMENTATION PROBLEM SIGNAL NO IS : 8

(25)

Write a program which demonstrates the shared memory functions PROGRAM SHM_PROCESS1 #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define SHMSZ 27 main() { char c; int shmid; key_t key; char *shm, *s; key = 5678;

if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {

printf("\n Error while creating memory segment"); exit(1);

}

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {

printf("\n Error while attatching to address space"); exit(1); } s = shm; for (c = 'a'; c <= 'z'; c++) *s++ = c; *s = NULL; while (*shm != '*') sleep(1);

printf("\n another process had red the data"); exit(0); } SHM_PROCESS2 #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h>

(26)

main() { int shmid; key_t key; char *shm, *s; key = 5678; if ((shmid = shmget(key, SHMSZ, 0666)) < 0)

{ printf("\n Error while locating the memory segment"); exit(1);

}

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { printf("\n Error while attatching the segment");

exit(1); } for (s = shm; *s != NULL; s++) putchar(*s); putchar('\n'); *shm = '*'; exit(0); } OUTPUT

First run the shm_process1 in background $> ./shm_process1 &

[1] 20319

After executing shm_proces1 creates a shared memory and writes a-z alphabets in it and waits for another process to read it and writes * to it.

Then run the shm_process2 $> ./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<stdio.h> #include<stdlib.h> #include<errno.h> #include<fcntl.h> #include<unistd.h>

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) {

(27)

printf("\n Usage : %s <filename>",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());

(28)

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

1. Set Read Lock 2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 1

Locked for reading by PID 3323 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 2

Locked for writing by PID 3323 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice :

Process 2

1. Set Read Lock 2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 1

Locked for reading by PID 3326 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 3

Read / Write Lock Unseted for PID 3326 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice :

Write a program demonstrating semaphore operation on a shared file for reading but not writing PROGRAM #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<fcntl.h> #include<unistd.h> #include<sys/sem.h> #include<sys/ipc.h> #include<unistd.h>

int main(int argc, char *argv[]) {

struct flock fl; int fd, ch, semid, sc; struct sembuf sem_op; fl.l_whence=SEEK_SET;

(29)

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 <filename>",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) {

(30)

} 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)<1) { sem_op.sem_op=1; semop(semid,&sem_op,1); } if(fcntl(fd,F_SETLK,&fl)==-1) {

printf("\n Error in fcntl while unseting Read / Write Lock");

exit(6); }

else

printf("\n Read / Write Lock Unseted for PID %d ",getpid()); } else if(ch==4) { if((sc=semctl(semid,0,SETVAL,1))==-1) {

printf("\n Error in semctl while initilizing semophore"); exit(7);

} break; }

else

printf("\n Enter choice between 1 to 4 only"); } }

OUTPUT

After compilation execute the program in two terminals. If one process sets the lock for reading, if another process will tries to lock for reading, it will be blocked by the semaphore.

Process 1

1. Set Read Lock 2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 1

Locked for reading by PID 4728 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 3

Read / Write Lock Unseted for PID 4728 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

(31)

Enter your choice : 4 Process 2

1. Set Read Lock 2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 1

Locked for reading by PID 4757 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

Enter your choice : 3

Read / Write Lock Unseted for PID 4757 1. Set Read Lock

2. Set Write Lock

3. Unset Read / Write Lock 4. Exit

(32)

File type Number of links

Read, write and execute permissions Time of last access

(Note: use stat/fstat system calls) PROGRAM #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<string.h> #include<stdlib.h>

int main(int argc, char *argv[]) {

int i=1;

char ftype[100]; struct stat StatusBuffer; if(argc<2)

{

printf("\n Arguments not specified properly \n"); printf("\n Usage : filename <file_list>\n\n"); exit(1); } while(i<argc) { if((lstat(argv[i],&StatusBuffer))==-1) {

printf("\n --- %s Invalid Filename specified --- \n",argv[i]); i++;

continue; }

printf("\n %s - File Status Information",argv[i]); printf("\n ---\n"); if(S_ISREG(StatusBuffer.st_mode)) strcpy(ftype,"Regular File"); else if(S_ISDIR(StatusBuffer.st_mode)) strcpy(ftype,"Directory File"); else if(S_ISLNK(StatusBuffer.st_mode)) strcpy(ftype,"Link File"); else

strcpy(ftype,"Special File or Unknown File"); printf("\n File Type : %s",ftype);

printf("\n I-node no of the file : %ld",StatusBuffer.st_ino); printf("\n Permission mode : %o",StatusBuffer.st_mode & 0777); printf("\n No of Links to the file : %ld",StatusBuffer.st_nlink); printf("\n size of the file : %ld",StatusBuffer.st_size); printf("\n Last access time : %ld",StatusBuffer.st_atime); printf("\n");

i++; }} out put:

(33)

#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<stdlib.h>

int main(int argc, char *argv[]) {

int i=1;

struct stat StatusBuffer; if(argc!=3)

{

printf("\n Arguments not specified properly \n"); printf("\n Usage : filename <source> <target>\n\n"); exit(1);

}

if((lstat(argv[1],&StatusBuffer))==-1) {

printf("\n Invalid source Filename specified \n",argv[1]); exit(2);

}

if(link(argv[1],argv[2])==-1) {

printf("\n Error While Moving"); exit(3);

}

else if(unlink(argv[1])==-1) {

unlink(argv[2]);

printf("\n Error While Moving"); exit(4);

} else

printf("\n File Moved or Renamed Sucessfully"); }

(34)

PROGRAM #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<stdlib.h> #include<fcntl.h> #define SIZE 1024

#define MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) int main(int argc, char *argv[])

{ int srcfd,dstfd; int nbytes; char buff[SIZE]; if(argc!=3) {

printf("\n Arguments not specified properly \n"); printf("\n Usage : filename <source> <target>\n\n"); exit(1);

}

if((srcfd=open(argv[1],O_RDONLY))==-1) {

printf("\n Invalid Filename or File cannot open"); exit(2);

}

if((dstfd=creat(argv[2],MODE))==-1) {

printf("\n Error while creating destination file"); close(srcfd); exit(3); } while((nbytes=read(srcfd,buff,SIZE))>0) { write(dstfd,buff,nbytes); } close(dstfd); close(srcfd);

printf("\n File Copied Sucessfully \n\n"); }

(35)

PROGRAM #include<stdio.h> #include<stdio.h> #include<dirent.h> #include<unistd.h> #include<sys/types.h> 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

(36)

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

(37)

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 <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) { 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)

(38)

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

References

Related documents

Using a script: You can write a shell script (Linux and Unix-like systems) or batch file (Windows) to report custom metrics every minute to the Standalone Machine Agent. The

Turn on echo option, display each line in script (with variable expansion/substation) before execution.  bash

The case statement in addition bash script does miss work purpose is the snippet of nut shell script usageUsage n servicer service argument hn.. Let's use this three-line unique

The product range is varied and includes The Italian Classic Deli Meats, such as Parma Ham (P.D.O.), Salame Felino (P.G.I.), Coppa di Parma (P.G.I.), Mortadella Bologna (P.G.I.),

This paper contributes to the existing literature on immigration by in- vestigating the causality relationship between immigration and host country economic conditions (unemployment

Proposed combination scheme with PCR6 rule yields the best verification accuracy compared to the statistical match score combination algorithms and DS theory-based combination

The PCM+ 4.0 Maintenance License for new installation covers the first year of use and allows for Technical Support and Software Updates.. After the first year is over, a new PCM+

Abstract In a game theoretical setting it is possible to assign a relative measurement of the skill required to each player for maximizing his payoff in a casino game; according to