Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

LINUX PROGRAMMING LAB MANUEL

LIST OF EXPERIMENTS

Exp1: 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. Exp2: Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it. Exp3: Write a shell script that displays a list of all the files in the current directory to which the user has read, write and execute permissions. Exp 4: Write a shell script that receives any number of filenames as arguments checks if every argument supplied is a file or a directory and reports accordingly. Whenever the argument is a line, the number of lines on it also reported. Exp5: Write a shell script that accepts a list of file names as its arguments, counts and reports the occurrences of each word that is present in the first argument file on other argument files Exp6: Write a shell script to list all of the directory files in a directory Exp7: Write a shell script to find factorial of a given number Exp 8: Write an awk script to account the number of lines in a file that do not contains vowels Exp 9: Write an awk script to find the number of characters, words, and lines in a file. Exp 10: Write a C Program that makes a copy of a file using standard I/O and system calls. Exp 11: Implement in C the following Unix commands using System calls. a) cat b) ls c)mv Exp12: Write a C program that takes one or more file or directory names as command line input and reports the following information on the file. a) File type b) Number of Links c) Time of last access d) Read , write and Execute permissions Exp 13: Write a C Program to emulate the Unix ls-l command Exp 14: Write a C Program to list for every file in a directory, its inode number and filename. Exp 15: Write a C Program that demonstrates redirection of standard output to a file. Ex ls>f1. Exp 16: Write a C Program to create a child process and allow the parent to display parent and the child to display child on the screen.

Exp 17: Write a C Program to create a Zombie process. Exp 18: Write a C Program that illustrates how an Orphan is created. Exp19:Write a C Program that illustrates how to execute two commands concurrently with a command pipe Ex ls-l|sort Exp 20: Write a C Programs that illustrates communication between two unrelated process using named pipes. Exp 21: Write a C Program to create a message queue with read and write permissions to write 3 messages to it with different priority numbers. Exp 22: Write a C Program that receives the messages ( from the above message queue as specified in Program 21 ) and displays them. Exp 23: Write a C Program to allow cooperating processes to lock a resource for exclusive use, using a) Semaphores b) flock or lockf system calls Exp 24: Write a C Program that illustrates suspending and resuming processes using signals. Exp 25: Write a C Program that implements a Producer-Consumer system with two processes. (using Semaphores) Exp 26: Write a client and server programs using C for interaction between server and client processes using Unix Domain sockets. Exp 27: Write a client and server programs using C for interaction between server and client processes using Internet Domain sockets. Exp 28: Write a C Program that illustrates two processes communicating using shared memory.

Exp1: 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.

#!/bin/bash FILENAME=$1 SL=$2 EL=$3 count=1 cat $FILENAME | while read LINE do if [ $count -ge $SL ] then if [ $count -le $EL ] then echo "$count.$LINE" fi fi count=`expr $count + 1` done

Exp2: Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it.

#!/bin/bash if [ $# -lt 1 ] then echo "Usage: exp2.sh <filename1><...>" else echo "Input a word" read word for file in $* do grep -iv "$word" $file |tee $file done echo "done.." fi

Exp3: Write a shell script that displays a list of all the files in the current directory to which the user has read, write and execute permissions #!/bin/sh read -p "Enter a directory name:" dn if [ -d $dn ] then echo "Files in the directory $dn are :" for "$fn" in `ls $dn` do if [-d $dn/$fn ] then echo "$fn Directory" elif [ -f $dn/$fn ] then echo "$fn files" fi if [ -r $dn/$fn ] then echo " read" fi if [ -w $dn/$fn ] then echo "write" fi if [ -x $dn/$fn ] then echo "Execute" fi echo "done" echo "$dn not exists or not a directory" Exp 4: Write a shell script that receives any number of filenames as arguments checks if every argument supplied is a file or a directory and reports accordingly. Whenever the argument is a line, the number of lines on it also reported. #!/bin/bash if [ $# -lt 1 ] then echo "Usage: exp4.sh <filename1 or directory1><....>" exit fi for file do

ls|grep -w "$file">/dev/null if [ $? -ne 0 ] then echo "$file: File or Directory does not exists" else ls -l |grep "^[^d]" |cut -c 57- |grep -w "$file" >/dev/null if [ $? -eq 0 ] then echo "Filename: $file -> `wc -l < $file` Lines" else echo "Directory:$file" fi fi done

Exp5: Write a shell script that accepts a list of file names as its arguments, counts and reports the occurrences of each word that is present in the first argument file on other argument files

#!/bin/sh if [ $# -lt 2 ] then echo "usage : wrdcnt wordfile filename1 filename2.." exit fi for word in `cat $1` do for file in $* do if [ "$file" != "$1" ] then echo "The word frequency of --$word-- in file $file is : `grep -iow "$word" $file|wc -w`" fi done done

Exp7: Write a shell script to find factorial of a given number #!/bin/bash echo "enter a number" read num i=2 res=1 if [ $num -ge 2 ] then while [ $i -le $num ] do res=`expr $res \* $i` i=`expr $i + 1` done fi echo "Factorial of $num="$res

Exp 11: Implement in C the following Unix commands using System calls. a) cp b) ls c)mv

a) /* Implementing cp command in C language */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> int main(int argc, char *argv[]) { int i,ifd,ofd,nr,nw; if(argc != 3) { fprintf(stderr,"Usage:<src> <dst> %s\n",argv[0]); exit(1); } ifd = open(argv[1],O_RDONLY); if(ifd < 0){ fprintf(stderr,"%s:Cannot open %s \n",argv[0],argv[1]); exit(2); } ofd = open(argv[2],O_WRONLY|O_CREAT,0644); if(ofd < 0) {

fprintf(stderr,"%s: cannot creat %s\n",argv[0],argv[2]); exit(3); } while(1){ char buff[512]; nr = read(ifd,buff,512); if(nr <= 0) break; nw = write(ofd,buff,nr); if(nw != nr) { fprintf(stderr,"%s: cannot write full data nr: %d nw %d\n",argv[0],(int)nr,(int)nw); exit(4); } } close(ifd); close(ofd); return 0; }

b) /* Implement ls command */ #include<stdio.h> #include<stdlib.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <string.h> int comp(const void *a,const void *b){ return strcasecmp((char*)a,(char *)b); } struct fd{ char fname[100]; int ftype; }x[200]; void main(){ int fc=0,dc=0,i=0,j; struct dirent *dptr; DIR *dir; char buff[256]; getcwd(buff, 256); printf("%s\n",buff); dir=opendir(buff); if(dir==NULL) { printf("Error in opening:%s\n",buff);

exit(1); } while(dptr=readdir(dir)) { if(dptr->d_name[0]!='.'){ strcpy(x[i].fname,dptr->d_name); x[i++].ftype= dptr->d_type; } } closedir(dir); qsort(x,i,sizeof(struct fd),comp); for(j=0;j<i;j++){ if(x[j].ftype==4){ dc++; printf("\E[31m"); printf("%s\n",x[j].fname); printf("\E[0m"); } else{ fc++; printf("\E[36m"); printf("%s\n",x[j].fname); printf("\E[0m"); } } printf("\E[34m"); printf("Total Directories:%3d\nTotal files:%3d\n",dc,fc); printf("\E[0m"); exit(0); }

c) /* Implement mv command in C */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> int main(int ac, char **av) { int s; if(ac !=3){ fprintf(stderr,"Usage:%s <src> <dst>\n",av[0]); exit(1); }

s=rename(av[1],av[2]); if(s < 0){ perror("rename:"); } return 0; }

Exp 10: Write a C Program that makes a copy of a file using standard I/O and system calls. a) /* A file copy program */ #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> int main() { char block[1024]; int in,out,nread; in=open("file.in",O_RDONLY); out=open("file.out",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR); while((nread = read(in,&block,sizeof(block)))>0) write(out,&block,nread); exit(0); } Exp12: Write a C program that takes one or more file or directory names as command line input and reports the following information on the file. a) File type b) Number of Links c) Time of last access d) Read , write and Execute permissions #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]) { struct stat filestat; int i, file=0; printf("Pass the file directory at the cmd prompt\n"); if(argc < 2) return 1;

for(i=1;i<argc;i++){ if(( file = open(argv[i],O_RDONLY)) < -1) continue; if(fstat(file, &filestat) < 0) continue; printf("Information for %s\n",argv[i]); printf("------------------------------------------------------------\n"); printf(FileType:\t %s\n,(int)filestat.st_mode & S_IFMT); printf("File Size: \t%d bytes\n",(int)filestat.st_size); printf("Number of links:\t%d\n",(int)filestat.st_nlink); printf("File inode: \t%d\n",(int)filestat.st_ino); printf(Last access time: %s\n,(int) filestat.st_ctime); printf("File Permissions:\t "); printf((S_ISDIR(filestat.st_mode))?"d":"-"); printf((filestat.st_mode & S_IRUSR)?"r":"-"); printf((filestat.st_mode & S_IWUSR)?"w":"-"); printf((filestat.st_mode & S_IXUSR)?"x":"-"); printf((filestat.st_mode & S_IRGRP)?"r":"-"); printf((filestat.st_mode & S_IWGRP)?"w":"-"); printf((filestat.st_mode & S_IXGRP)?"x":"-"); printf((filestat.st_mode & S_IROTH)?"r":"-"); printf((filestat.st_mode & S_IWOTH)?"w":"-"); printf((filestat.st_mode & S_IXOTH)?"x":"-"); printf("\nThe file %s a symbolic link \n",(S_ISLNK(filestat.st_mode))?"is":"is not"); close(file); } return 0; }

Exp 13: Write a C Program to emulate the Unix ls-l command /* Implementing ls -l command in C program using system calls */ #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]) { struct stat filestat;

int i, file=0; printf("Pass the file directory at the cmd prompt\n"); if(argc < 2) return 1; for(i=1;i<argc;i++){ if(( file = open(argv[i],O_RDONLY)) < -1) continue; if(fstat(file, &filestat) < 0) continue; printf("Information for %s\n",argv[i]); printf("--------------------------\n"); printf("File Size: \t%d bytes\n",(int)filestat.st_size); printf("Number of links:\t%d\n",(int)filestat.st_nlink); printf("File inode: \t%d\n",(int)filestat.st_ino); printf("File Permissions:\t "); printf((S_ISDIR(filestat.st_mode))?"d":"-"); printf((filestat.st_mode & S_IRUSR)?"r":"-"); printf((filestat.st_mode & S_IWUSR)?"w":"-"); printf((filestat.st_mode & S_IXUSR)?"x":"-"); printf((filestat.st_mode & S_IRGRP)?"r":"-"); printf((filestat.st_mode & S_IWGRP)?"w":"-"); printf((filestat.st_mode & S_IXGRP)?"x":"-"); printf((filestat.st_mode & S_IROTH)?"r":"-"); printf((filestat.st_mode & S_IWOTH)?"w":"-"); printf((filestat.st_mode & S_IXOTH)?"x":"-"); printf("\nThe file %s a symbolic link \n",(S_ISLNK(filestat.st_mode))?"is":"is not"); close(file); } return 0; } Exp 14: Write a C Program to list for every file in a directory, its inode number and filename. #include <stdio.h> #include <sys/types.h> #include<stdlib.h> #include<dirent.h> int main(int argc,char *argv[]) { Struct dirent *de; DIR *d; d=open(argv[1]); if(d == NULL)

{ printf(Directory is not opened\n); exit(1); } while((de=readdir(d)) != NULL) { printf(filename: %s\n,de->d-name); printf(inode no:%d\n,(int)de->d_ino); } closedir(d); return 0; }

Exp15 Write a C Program that demonstrates redirection of standard output to a file. Ex ls-l|sort.

a) /* Implementing the command ls -l|sort */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> int main() { int in,out; char *ls_args[]={"ls","-l","|","sort",NULL}; in = open("test.c",O_RDONLY); out = open("f22",O_WRONLY|O_TRUNC|O_CREAT,00777); dup2(in,0); // replace stdin with input file dup2(out,1); // replace stdout with output file close(in); close(out); // execute grep cmd execvp("ls",ls_args); return 0; }

Exp 15: Write a C Program that demonstrates redirection of standard output to a file. Ex ls>f1. b) /* Implementing the command ls > f1 */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> int main() { int in,out; char *ls_args[]={"ls",NULL}; in = open("test.c",O_RDONLY); out = open("f1",O_WRONLY|O_TRUNC|O_CREAT,00777); dup2(in,0); // replace stdin with input file dup2(out,1); // replace stdout with output file close(in); close(out); // execute grep cmd execvp("ls",ls_args); return 0; } Exp 15: Write a C Program that demonstrates redirection of standard output to a file. Ex ls|wc. c) /* Implement the ls|wc command using C programs */ #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> int main() { int k,fd[2],pid; k = pipe(fd); if(k == -1) { perror("error in creating pipe"); exit(1);

} pid= fork(); if(pid == -1){ printf("fork failed"); exit(2); } if(pid != 0) { close(fd[0]); // closing read end of pipe dup2(fd[1],1); // redirecting stdout to a file close(fd[1]); // closing write end of pipe execl("/bin/ls","ls",NULL); // execute the ls command perror("error in executing ls cmd"); } else{ close(fd[1]); // closing write end of pipe dup2(fd[0],0); // redirecting stdin from a file close(fd[0]);//closing read end of the pipe execl("/usr/bin/wc","wc",NULL); // execute the ws command perror("error in executing wc cmd"); } return 0; } Exp 16: Write a C Program to create a child process and allow the parent to display parent and the child to display child on the screen. #include<stdio.h> #include <sys/types.h> int main(void) { pid_t pid; printf(Before Fork \n); pid=fork(); if(pid >0) /* Parent Process */ { sleep(1); printf(Parent PID: %d , PPID: %d, CHILD PID: %d\n,getpid(),getppid(),pid); } else if(pid == 0) { printf(Child-PID: %d PPID: %d\n,getpid(),getppid()); } else{

printf(Fork Error); exit(1); } printf(Both Processes continue from here \n); }

Exp 17: Write a C Program to create a Zombie process. #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main() { pid_t child_pid; child_pid = fork(); if(child_pid > 0) { sleep(60); } else{ exit(0); } return 0; }

Exp 18: Write a C Program that illustrates how an Orphan is created. #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main() { pid_t child_pid; child_pid = fork(); if(child_pid > 0) /* child process */ { exit(0);

} else{ /* parent process */ sleep(60); } return 0; }

Exp19:Write a C Program that illustrates how to execute two commands concurrently with a command pipe Ex ls-l|sort #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> int main() { int in,out; char *ls_args[]={"ls","-l","|","sort",NULL}; in = open("test.c",O_RDONLY); out = open("f22",O_WRONLY|O_TRUNC|O_CREAT,00777); dup2(in,0); // replace stdin with input file dup2(out,1); // replace stdout with output file close(in); close(out); // execute grep cmd execvp("ls",ls_args); return 0; }

Exp 20: Write a C Programs that illustrates communication between two related process using named pipes. #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { int n,fd[2]; pid_t pid; char buf[50]; char msg[50]="Hello! Welcome to Linux World\n"; if(pipe(fd) == -1){ printf(" Can't create the pipe\n"); exit(1); } if((pid = fork()) == -1){ printf("Can't create the child\n"); exit(2); } else if(pid > 0) { close(fd[0]); // parent close read end of pipe write(fd[1],msg,sizeof(msg));// parent writes to the pipe } else{ close(fd[1]); // child closes write end of pipe n=read(fd[0],buf,sizeof(buf)); //child reads from the pipe write(STDOUT_FILENO,buf,n); // Displays on the stdout } return 0; }

Exp23: Handling Zombie Process by Using Signal Handler /* Handling Zombie Process by using signal handler */ #include <stdio.h> #include <unistd.h> #include <signal.h> #include <stdlib.h>

void sig_handler(int signo){ int cpid,status; cpid = wait(&status); printf("\nCPID= %d SIGNO = %d STATUS =%d Child Terminated\n",cpid,signo,status); } int main(){ int pid; signal(SIGCLD,sig_handler); pid = fork(); if(pid == 0) { while(1); exit(0); } else{ while(1); sleep(2000); } return 0; }

Exp 24: Write a C Program that illustrates suspending and resuming processes using signals. /* Handling sigaction function */ #include <stdio.h> #include <signal.h> #include <sys/types.h> void myhandler(int sig) { printf("In Myhandler signo: %d\n",sig); } int main() { struct sigaction old,new; sigset_t set; sigemptyset(&set); sigfillset(&set); new.sa_handler = myhandler;

new.sa_mask = set; new.sa_flags = 0; printf("To handle your handler!! press ctlr C\n"); sigaction(SIGINT,&new,&old); // myhandler signal will be invoked pause(); printf("To handle Default handler!! press ctrl C now..\n"); sigaction(SIGINT,&old,NULL); // default handler will be invoked pause(); return 0; }

Exp25: Write a C Program to Implement the Thread Mutex Synchronization #include <stdio.h> #include <pthread.h> int global=5; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; void *func(void *str) { pthread_mutex_lock(&mut); global++; pthread_mutex_unlock(&mut); printf(" Thread %s global %d\n",(char *)str,global); pthread_exit("success"); } int main() { void *msg; pthread_t pth1,pth2; pthread_create(&pth1,NULL,func,"first"); pthread_create(&pth2,NULL,func,"second"); pthread_join(pth1,&msg); printf("First Thread termination: %s\n",(char *)msg); pthread_join(pth2,&msg); printf("Second Thread termination: %s\n",(char *)msg); }

Exp 26: Write a client and server programs using C for interaction between server and client processes using Unix Domain sockets.

/* TCP Client */ #include <stdio.h> #include <netinet/in.h> #include <time.h> #include<sys/socket.h> #include <strings.h> #include <arpa/inet.h> #define MAXSIZE 512 main(int argc,char * argv[]){ int i,sfd; char buff[MAXSIZE]; struct sockaddr_in servaddr; sfd=socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof( servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(6000); inet_pton(AF_INET,argv[1], &servaddr.sin_addr); connect(sfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); i =read(sfd,buff,MAXSIZE); if(i<=0)printf("NO REsponse\n"); else{ buff[i]=0; printf("Todays time and date: %s",buff); } close(sfd); } /* TCP Server */ #include <stdio.h> #include <netinet/in.h> #include <time.h> #include<sys/socket.h> #include <string.h> #define MAXSIZE 1000 main(int argc,char * argv[]){ int i,sfd,cfd; char buff[MAXSIZE]; time_t t; struct sockaddr_in servaddr,cliaddr; sfd=socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof( servaddr)); servaddr.sin_family=AF_INET;

servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(6000); bind(sfd,(struct sockaddr *) &servaddr,sizeof(servaddr)); listen(sfd,5); while(1){ i=sizeof cliaddr; printf("Waiting for a client..........\n"); cfd=accept(sfd,(struct sockaddr *) &cliaddr,&i); printf("Port No:%d\n",ntohs(cliaddr.sin_port)); printf("IP Address :%s\n", (char *)inet_ntop(AF_INET,&cliaddr.sin_addr,buff,MAXSIZE)); t=time(NULL); snprintf(buff,MAXSIZE,"%s\n",ctime(&t)); write(cfd,buff,strlen(buff)); close(cfd); } }

Exp 27: Write a client and server programs using C for interaction between server and client processes using Internet Domain sockets.

/* UDP Client */ #include <stdio.h> #include <netinet/in.h> #include<sys/socket.h> #include <string.h> #include <arpa/inet.h> #define MAXSIZE 512 main(int argc,char * argv[]){ int i,sfd,len; char buff[MAXSIZE]; struct sockaddr_in servaddr,cliaddr; if(argc != 2){printf("specify server IP\n");goto END;} sfd=socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof( servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(6000); printf("enter a string:"); gets(buff); sendto(sfd,buff,strlen(buff),0,(struct sockaddr *)&servaddr,sizeof(servaddr)); i=recvfrom(sfd,buff,MAXSIZE,0,NULL,NULL); buff[i]=0; printf(" %s\n",buff); END:

printf("DONE"); } /* UDP server */ #include <stdio.h> #include <netinet/in.h> #include<sys/socket.h> #include <string.h> #include <arpa/inet.h> #define MAXSIZE 512 main(int argc,char * argv[]){ int i,sfd,len; char buff[MAXSIZE]; struct sockaddr_in servaddr,cliaddr; if(argc != 2){printf("specify server IP\n");goto END;} sfd=socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof( servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(6000); printf("enter a string:"); gets(buff); sendto(sfd,buff,strlen(buff),0,(struct sockaddr *)&servaddr,sizeof(servaddr)); i=recvfrom(sfd,buff,MAXSIZE,0,NULL,NULL); buff[i]=0; printf(" %s\n",buff); END: printf("DONE"); }

Exp 28: Write a C Program that illustrates two processes communicating using shared memory. #include<stdlib.h> #include<string.h> #include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #define KEY1 654320L #define KEY2 1265432L #define PERMS 0666 #define MAXSIZE 2048

static struct sembuf op_lock[2]={ 0,0,0, 0,1,0 }; static struct sembuf op_unlock[1]={ 0,-1,IPC_NOWAIT }; void my_lock(int semid){ semop(semid,&op_lock[0],2); } void my_unlock(int semid){ semop(semid,&op_unlock[0],1); } main() { int semid,shmid; int pid,*id,i; pid=getpid(); semid=semget(KEY1,1,IPC_CREAT | PERMS); shmid=shmget(KEY2,sizeof(int),IPC_CREAT | PERMS); for(i=1;i<5;i++){ my_lock(semid); printf("process %d is in CS\n",pid); id=(int *)shmat(shmid,0,0); printf("id read is %d \n",*id); *id=*id+1; sleep(5); shmdt((char *) id); my_unlock(semid); } printf("process %d is complete\n",pid); }

You might also like