lp lab manuel

Upload: ravi-kumar-lanke

Post on 14-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Lp Lab Manuel

    1/23

    LINUX PROGRAMMING LAB MANUEL

    LIST OF EXPERIMENTS

    Exp1: Write a shell script that accepts a file name, starting and ending line numbers asarguments 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 filessupplied as arguments to it.

    Exp3: Write a shell script that displays a list of all the files in the current directory to which theuser has read, write and execute permissions.

    Exp 4: Write a shell script that receives any number of filenames as arguments checks if everyargument supplied is a file or a directory and reports accordingly. Whenever the argument is aline, 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 theoccurrences 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 inputand reports the following information on the file.a) File type b) Number of Linksc) 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 andthe child to display child on the screen.

  • 7/30/2019 Lp Lab Manuel

    2/23

    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 usingnamed pipes.

    Exp 21: Write a C Program to create a message queue with read and write permissions to write 3messages to it with different priority numbers.

    Exp 22: Write a C Program that receives the messages ( from the above message queue asspecified 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 twoprocesses. (using Semaphores)

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

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

    Exp 28: Write a C Program that illustrates two processes communicating using sharedmemory.

  • 7/30/2019 Lp Lab Manuel

    3/23

    Exp1: Write a shell script that accepts a file name, starting and ending line numbers asarguments and displays all the lines between the given line numbers.

    #!/bin/bashFILENAME=$1SL=$2EL=$3count=1cat $FILENAME | while read LINEdoif [ $count -ge $SL ]then

    if [ $count -le $EL ]

    thenecho "$count.$LINE"fi

    ficount=`expr $count + 1`done

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

    #!/bin/bashif [ $# -lt 1 ]thenecho "Usage: exp2.sh "

    elseecho "Input a word"read wordfor file in $*dogrep -iv "$word" $file |tee $filedoneecho "done.."fi

  • 7/30/2019 Lp Lab Manuel

    4/23

    Exp3: Write a shell script that displays a list of all the files in the current directory to which theuser has read, write and execute permissions

    #!/bin/sh

    read -p "Enter a directory name:" dnif [ -d $dn ]thenecho "Files in the directory $dn are :"for "$fn" in `ls $dn`doif [-d $dn/$fn ]thenecho "$fn Directory"elif [ -f $dn/$fn ]then

    echo "$fn files"fiif [ -r $dn/$fn ]thenecho " read"

    fi

    if [ -w $dn/$fn ]thenecho "write"

    fiif [ -x $dn/$fn ]thenecho "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 everyargument supplied is a file or a directory and reports accordingly. Whenever the argument is aline, the number of lines on it also reported.

    #!/bin/bashif [ $# -lt 1 ]thenecho "Usage: exp4.sh "exit

    fifor filedo

  • 7/30/2019 Lp Lab Manuel

    5/23

    ls|grep -w "$file">/dev/nullif [ $? -ne 0 ]then

    echo "$file: File or Directory does not exists"else

    ls -l |grep "^[^d]" |cut -c 57- |grep -w "$file" >/dev/nullif [ $? -eq 0 ]then

    echo "Filename: $file -> `wc -l < $file` Lines"else

    echo "Directory:$file"fi

    fidone

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

    #!/bin/shif [ $# -lt 2 ]then

    echo "usage : wrdcnt wordfile filename1 filename2.."exit

    fifor word in `cat $1`dofor file in $*doif [ "$file" != "$1" ]then

    echo "The word frequency of --$word-- in file $file is :`grep -iow "$word" $file|wc -w`"

    fidonedone

  • 7/30/2019 Lp Lab Manuel

    6/23

    Exp7: Write a shell script to find factorial of a given number

    #!/bin/bashecho "enter a number"read num

    i=2res=1if [ $num -ge 2 ]thenwhile [ $i -le $num ]dores=`expr $res \* $i`i=`expr $i + 1`donefiecho "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 #include #include #include

    int main(int argc, char *argv[]){int i,ifd,ofd,nr,nw;if(argc != 3){fprintf(stderr,"Usage: %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){

  • 7/30/2019 Lp Lab Manuel

    7/23

    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

  • 7/30/2019 Lp Lab Manuel

    8/23

    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

  • 7/30/2019 Lp Lab Manuel

    9/23

    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 #include #include #include

    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 inputand reports the following information on the file.a) File type b) Number of Linksc) Time of last access d) Read , write and Execute permissions

    #include #include #include #include #include

    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;

  • 7/30/2019 Lp Lab Manuel

    10/23

    for(i=1;i

  • 7/30/2019 Lp Lab Manuel

    11/23

    int i, file=0;printf("Pass the file directory at the cmd prompt\n");if(argc < 2)

    return 1;for(i=1;i

  • 7/30/2019 Lp Lab Manuel

    12/23

    {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 #include #include #include #include #include

    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 cmdexecvp("ls",ls_args);return 0;}

  • 7/30/2019 Lp Lab Manuel

    13/23

    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 #include

    #include #include #include #include

    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 cmdexecvp("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 #include #include #include

    int main(){int k,fd[2],pid;k = pipe(fd);if(k == -1){perror("error in creating pipe");exit(1);

  • 7/30/2019 Lp Lab Manuel

    14/23

    }pid= fork();if(pid == -1){printf("fork failed");exit(2);

    }if(pid != 0){close(fd[0]); // closing read end of pipedup2(fd[1],1); // redirecting stdout to a fileclose(fd[1]); // closing write end of pipeexecl("/bin/ls","ls",NULL); // execute the ls commandperror("error in executing ls cmd");}else{close(fd[1]); // closing write end of pipe

    dup2(fd[0],0); // redirecting stdin from a fileclose(fd[0]);//closing read end of the pipeexecl("/usr/bin/wc","wc",NULL); // execute the ws commandperror("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 andthe child to display child on the screen.

    #include#include

    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{

  • 7/30/2019 Lp Lab Manuel

    15/23

    printf(Fork Error);exit(1);

    }printf(Both Processes continue from here \n);}

    Exp 17: Write a C Program to create a Zombie process.

    #include #include #include

    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 #include #include

    int main(){pid_t child_pid;child_pid = fork();if(child_pid > 0) /* child process */{

    exit(0);

  • 7/30/2019 Lp Lab Manuel

    16/23

    }else{ /* parent process */

    sleep(60);}return 0;

    }

    Exp19:Write a C Program that illustrates how to execute two commands concurrently with acommand pipe Ex ls-l|sort

    #include #include

    #include #include #include #include

    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 cmdexecvp("ls",ls_args);

    return 0;}

  • 7/30/2019 Lp Lab Manuel

    17/23

    Exp 20: Write a C Programs that illustrates communication between two related process usingnamed pipes.

    #include #include

    #include 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 pipewrite(fd[1],msg,sizeof(msg));// parent writes to the pipe}else{close(fd[1]); // child closes write end of pipen=read(fd[0],buf,sizeof(buf)); //child reads from the pipewrite(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 #include #include #include

  • 7/30/2019 Lp Lab Manuel

    18/23

    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 #include #include

    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;

  • 7/30/2019 Lp Lab Manuel

    19/23

    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 invokedpause();

    printf("To handle Default handler!! press ctrl C now..\n");sigaction(SIGINT,&old,NULL); // default handler will be invokedpause();

    return 0;}

    Exp25: Write a C Program to Implement the Thread Mutex Synchronization

    #include #include

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

  • 7/30/2019 Lp Lab Manuel

    20/23

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

    /* TCP Client */

    #include #include #include #include#include #include #define MAXSIZE 512main(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

  • 7/30/2019 Lp Lab Manuel

    21/23

    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 clientprocesses using Internet Domain sockets.

    /* UDP Client */#include #include #include#include #include #define MAXSIZE 512main(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:

  • 7/30/2019 Lp Lab Manuel

    22/23

    printf("DONE");}

    /* UDP server */

    #include #include #include#include #include #define MAXSIZE 512main(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 sharedmemory.

    #include#include#include#include#include#include#define KEY1 654320L#define KEY2 1265432L#define PERMS 0666#define MAXSIZE 2048

  • 7/30/2019 Lp Lab Manuel

    23/23

    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