Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record 1 Linux Programming No: 1 AIM: Write a Shell script that accepts a filename, starting and ending line numbers as arguments and displays all the lines between the given line numbers. Program: echo "enter the filename" read fname echo "enter the starting line number" read s echo "enter the ending line number" read n sed -n $s,$n\p $fname | cat > newline cat newline output: [root@localhost ~]# vi 1s.sh [root@localhost ~]# ./1s.sh bash: ./1s.sh: Permission denied [root@localhost ~]# chmod 777 1s.sh [root@localhost ~]# ./1s.sh enter the filename sales.dat enter the starting line number 2 enter the ending line number 4 1 computers 9161 1 textbooks 21312 2 clothing 3252
40
Embed
Siddhartha Institute of Engineering & Technology, IBP. …siddhartha.ac.in/downloads/LP_Lab_Records.pdf · Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record 1 Linux
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
1
Linux Programming No: 1 AIM: Write a Shell script that accepts a filename, starting and ending line numbers as arguments and displays all the lines between the given line numbers. Program: echo "enter the filename" read fname echo "enter the starting line number" read s echo "enter the ending line number" read n sed -n $s,$n\p $fname | cat > newline cat newline output: [root@localhost ~]# vi 1s.sh
[root@localhost ~]# ./1s.sh
bash: ./1s.sh: Permission denied
[root@localhost ~]# chmod 777 1s.sh
[root@localhost ~]# ./1s.sh
enter the filename
sales.dat
enter the starting line number
2
enter the ending line number
4
1 computers 9161
1 textbooks 21312
2 clothing 3252
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
2
Linux Programming No: 2 AIM: Write a Shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it. Program: ## for this program we have to create one or more files (optional), ## I am creating two files names are del ,dell. [root@localhost ~]# vi del unix is os dos is also os here using unix unix is powerful os ~ [root@localhost ~]# vi dell windowsnt is also os there are some difference between unix and windowsnt but unix is great among all os ## after creation two files now we have to write sed script file name is del.sed using vi editor. [root@localhost ~]# vi del.sed { /os/d } Output: [root@localhost ~]# sed -f del.sed del dell
here using unix
there are some difference between unix and windowsnt
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
3
Linux Programming No: 3 AIM: Write a Shell script that displays list of all the files in the current directory to which the user has read, write and execute permissions. Program: echo "enter the directory name" read dir if [ -d $dir ] then cd $dir ls > f exec < f while read line do if [ -f $line ] then if [ -r $line -a -w $line -a -x $line ] then echo "$line has all permissions" else echo "files not having all permissions" fi fi done fi Output: $sh prg3.sh
enter the directory name
dir1
ff has all permissions
files not having permissions
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
4
Linux Programming No: 4 AIM: Write a Shell script that receives any number of file names as arguments checks if every argument supplied is a file or a directory and reports accordingly. Whenever the argument is a file, the number of lines on it is also reported. Program: for x in $* do if [ -f $x ] then echo " $x is a file " echo " no of lines in the file are " wc -l $x elif [ -d $x ] then echo " $x is a directory " else echo " enter valid filename or directory name " fi done Output: guest-glcbIs@ubuntu:~$sh lprg4.sh dir1 d1
dir1 is a directory
d1 is a file
no of lines in the file are 2
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
5
Linux Programming No: 5 AIM: Write a Shell script that accepts a list of file names as its arguments, counts and reports the occurrence of each word that is present in the first argument file on other argument files. Program: if [ $# -eq 0 ] then echo "no arguments" else tr " " " " < $1 > temp shift for i in $* do tr " " " " < $i > temp1 y=`wc -l < temp` j=1 while [ $j -le $y ] do x=`head -n $j temp | tail -1` c=`grep -c "$x" temp1` echo $x $c j=`expr $j 1` done done fi Output: $sh 9a.sh hegde.sh ravi.sh
Raghu 2
Hary 1
Vinay 9
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
6
Programming No: 6 AIM: Write a Shell script to list all of the directory files in a directory. Program: # !/bin/bash echo "enter directory name" read dir if[ -d $dir] then echo "list of files in the directory" ls –l $dir|egrep ‘^d’ else echo "enter proper directory name" fi Output: sh lprg6.sh
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
7
Linux Programming No: 7 AIM: Write a Shell script to find factorial of a given integer. Program: # !/bin/bash echo "enter a number" read num fact=1 while [ $num -ge 1 ] do fact=`expr $fact\* $num` num=’expr $num – 1’ done echo "factorial of $n is $fact" Output: guest-glcbIs@ubuntu:~$sh lprg7.sh
enter a number
4
Factorial of 4 is 24
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
8
Linux Programming No: 8 AIM: Write a awk script to find the number of characters, words and lines in a file. Program: BEGIN{print "record.\t characters \t words"} #BODY section { len=length($0) total_len =len print(NR,":\t",len,":\t",NF,$0) words =NF } END{ print("\n total") print("characters :\t" total len) print("lines :\t" NR) } Output: $ awk –f cnt.awk ff1
Record words
1: 5: 1hello
Total
Characters:5
Lines:1
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
9
Linux Programming No: 9 AIM: Write a C Program that makes a copy of a file using standard I/O and system calls. Program: #include <stdio.h> #include <unistd.h> #include <fcntl.h> void typefile (char *filename) { int fd, nread; char buf[1024]; fd = open (filename, O_RDONLY); if (fd == -1) { perror (filename); return; } while ((nread = read (fd, buf, sizeof (buf))) > 0) write (1, buf, nread); close (fd); } int main (int argc, char **argv) { int argno; for (argno = 1; argno < argc; argno ) typefile (argv[argno]); exit (0); } Output: $gcc –o prg10.out prg10.c
$cat > ff
hello
hai
$./prg10.out ff
hello
hai
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
10
Linux Programming No: 10 AIM: Implement in C the following Unix commands using system calls A). cat B). ls C). mv Program: A) cat #include<sys/types.h> #include<sys/stat.h> #include<stdio.h> #include<fcntl.h> main( int argc,char *argv[3] ) { int fd,i; char buf[2]; fd=open(argv[1],O_RDONLY,0777); if(fd==-argc) { printf("file open error"); } else { while((i=read(fd,buf,1))>0) { printf("%c",buf[0]); } close(fd); } } Output: $gcc –o prgcat.out prgcat.c
$cat > ff
hello
hai
$./prgcat.out ff
hello
hai
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
11
B) ls #include <sys/types.h> #include <sys/dir.h> #include <sys/param.h> #include <stdio.h> #define FALSE 0 #define TRUE 1 extern int alphasort(); char pathname[MAXPATHLEN]; main() { int count,i; struct dirent **files; int file_select(); if (getwd(pathname) == NULL ) { printf("Error getting pathn"); exit(0); } printf("Current Working Directory = %sn",pathname); count = scandir(pathname, &files, file_select, alphasort); if (count <= 0) { printf("No files in this directoryn"); exit(0); } printf("Number of files = %dn",count); for (i=1;i<count 1; i) printf("%s \n",files[i-1]->d_name); } int file_select(struct direct *entry) { if ((strcmp(entry->d_name, ".") == 0) ||(strcmp(entry->d_name, "..") == 0)) return (FALSE); else return (TRUE); } Output: $ gcc list.c
$ ./a.out
Current working directory=/home/student/
Number of files=57
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
13
Linux Programming No: 11 AIM: Write a C program that counts the number of blanks in a text file using standard I/O. Program: #include <fcntl.h> #include < sys/stat.h> #include <stdio.h> int main(int argc, char **argv) { FILE *fd1; int n,count=0; char buf; fd1=fopen(argv[1],"r"); while(!feof(fd1)) { buf=fgetc(fd1); if(buf==' ') count=count+1; } printf("\n Total Blanks= %d",count); return (0); }
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
14
Linux Programming No: 12 AIM: Write a Program that takes one or more file/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. Program: clear for i in $* do if [ -d $i ] then echo “Given directory name is found as $i” fi if [ -f $i ] then echo “Given name is a file as $i “ fi echo “Type of file/directory $i” file $i echo “Last access time is:” ls -l$i | cut-c 31-46 echo "no.of links" ln $i if [ -x $i –a -w $i-a –r $i ] then echo “$i contains all permission” else echo “$i does not contain all permissions” fi done Output: $sh prg12.sh ff1
given name is file ff1
Type of file/directory ff1
last access time
2014-09-07 10:1
No.of links
ff1 does not contain all permissions
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
15
Linux Programming No: 13 AIM: Write a C program to emulate the Unix ls-l command. Program: #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> int main() {
int pid; //process id pid = fork(); //create another process if ( pid < 0 ) { //fail
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
16
Linux Programming No: 14 AIM: Write a C program to list for every file in a directory,its inode number and file name. Program: #include<stdlib.h> #include<stdio.h> #include<string.h> main(int argc, char *argv[]) { char d[50]; if(argc==2) { bzero(d,sizeof(d)); strcat(d,"ls "); strcat(d,"-i "); strcat(d,argv[1]); system(d); } else printf("\nInvalid No. of inputs"); } output: $ mkdir dd
$ cd dd
/dd$ cat >f1
hello
^z
/dd$ cd
$gcc –o flist.out flist.c
$./flist.out dd
hello
46490 f1
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
17
Linux Programming No: 15 AIM: Write a C Program that demonstrates redirection of standard output to a file .EX:ls>f1. Program: #include<stdlib.h> #include<stdio.h> #include<string.h> main(int argc, char *argv[]) { char d[50]; if(argc==2) { bzero(d,sizeof(d)); strcat(d,"ls "); strcat(d,"> "); strcat(d,argv[1]); system(d); } else printf("\nInvalid No. of inputs"); } output: $ gcc –o std.out std.c
$ls
downloads documents listing.c listing.out std.c
std.out
$ cat > f1
^z
$./std.out f1
$cat f1
downloads
documents
listing.c
listing.out
std.c
std.out
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
18
Linux Programming No: 16 AIM: C Program to Create a child process and allow the parent to display “parent” and the child display “child” on the screen. Program: #include <stdio.h> #include <iostream> #include <string> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> void main() { int pid; pid = fork(); if (pid < 0) { // error occurred fprintf(stderr, "Fork failed!\n"); exit(-1); } else if (pid == 0) { // child process printf("I am the child, return from fork=%d\n", pid); execlp("/bin/ps", "ps", NULL); } else { // parent process printf("I am the parent, return from fork, child pid=%d\n", pid); printf("Parent exiting!\n"); exit(0); } } Output: $ ./a.out
I am the parent, return from fork, child pid=15053
Parent exiting!
I am the child, return from fork=0
$ PID TTY TIME CMD
15033 pts/0 00:00:00 tcsh
15053 pts/0 00:00:00 p
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
19
Linux Programming No: 17 AIM: Simple C Program to create Zombie Process. Program: #include<stdio.h> main() { int id; id=fork(); if(id>0) { printf("Parent will sleep"); sleep(10); } if(id==0) printf("I am child"); } OUTPUT $ cc zombie.c
$ ./a.out
I am child
Parent will sleep
$
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
20
Linux Programming No: 18 AIM: Simple C Program to create Orphan Process. Program: #include<stdio.h> #include<unistd.h> void main() { pid_t p; /* create child process */ p=fork(); if(p==0) { /* fork() returns Zero to child */ sleep(10); } printf("The child process pid is %d parent pid %d\n", getpid(), getppid()); /*parent/child waits for 20 secs and exits*/ sleep(20); printf("\nProcess %d is done its Parent pid %d...\n", getpid(), getppid()); } OUTPUT: $ cc arphan.c
$ ./a.out
The child process pid is 2575 parent pid 1922
The child process pid is 2576 parent pid 2575
Process 2575 is done its Parent pid 1922...
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
21
Linux Programming No: 19 AIM: A sample program to demonstrate how pipes are used in Linux Processes. Program: #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #define MSGLEN 64 void main() { int fd[2]; pid_t pid; int result; //Creating a pipe result = pipe (fd); if (result < 0) { //failure in creating a pipe perror("pipe"); exit (1); } //Creating a child process pid = fork(); if (pid < 0) { //failure in creating a child perror ("fork"); exit(2); } if (pid == 0) { //Child process char message[MSGLEN]; while(1) { //Clearing the message memset (message, 0, sizeof(message)); printf ("Enter a message: "); scanf ("%s",message); //Writing message to the pipe write(fd[1], message, strlen(message));
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
22
} exit (0); } else { //Parent Process char message[MSGLEN]; while (1) { //Clearing the message buffer memset (message, 0, sizeof(message)); //Reading message from the pipe read (fd[0], message, sizeof(message)); printf("Message entered %s\n",message); } exit(0); } }
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
23
Linux Programming No: 20 AIM: Write a C programs that illustrate communication between two unrelated processes using named pipe. Program: #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<unistd.h> int main() { int pfds[2]; char buf[30]; if(pipe(pfds)==-1) { perror("pipe"); exit(1); } printf("writing to file descriptor #%d\n", pfds[1]); write(pfds[1],"test",5); printf("reading from file descriptor #%d\n ", pfds[0]); read(pfds[0],buf,5); printf("read\"%s\"\n" ,buf); } Output: $ cc pipes1.c
$ ./a.out
writing to file descriptor #4
reading from file descriptor #3
read"test"
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
24
Linux Programming No: 21 AIM: Write a C program to create a message queue with read and write permissions to write 3 messages to it with different priority numbers. Program: #include <stdio.h> #include <sys/ipc.h> #include <fcntl.h> #define MAX 255 struct mesg { long type; char mtext[MAX]; } *mesg; char buff[MAX]; void main() { int mid,fd,n,count=0;; if((mid=msgget(1006,IPC_CREAT | 0666))<0) { printf(“\n Can’t create Message Q”); exit(1); } printf(“\n Queue id:%d”, mid); mesg=(struct mesg *)malloc(sizeof(struct mesg)); mesg ->type=6; fd=open(“fact”,O_RDONLY); while(read(fd,buff,25)>0) { strcpy(mesg ->mtext,buff); if(msgsnd(mid,mesg,strlen(mesg ->mtext),0)== -1) printf(“\n Message Write Error”); } if((mid=msgget(1006,0))<0) { printf(“\n Can’t create Message Q”); exit(1); } while((n=msgrcv(mid,&mesg,MAX,6,IPC_NOWAIT))>0) write(1,mesg.mtext,n); count ; if((n= = -1)&(count= =0)) printf(“\n No Message Queue on Queue:%d”,mid); } Output: $ gcc msgq.c
$ cat > fact
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
25
Hello
Hai
Welcome
^z
$ ./msgq.out
Queue id :0
Mesgq created
Hello
Hai
welcome
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
26
Linux Programming No: 22 AIM: Write a C program that receives the messages and display them. Program: #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #define MSGSZ 128 /* Declare the message structure. */
typedef struct msgbuf {
long mtype; char mtext[MSGSZ];
} message_buf; void main() { int msqid; key_t key; message_buf rbuf; /* Get the message queue id for the "name" 1234, which was created by the server. */ key = 1234; if ((msqid = msgget(key, 0666)) < 0) { perror("msgget"); exit(1); } /* Receive an answer of message type 1. */ if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) { perror("msgrcv"); exit(1); } /* Print the answer. */ printf("%s\n", rbuf.mtext); } Execution Steps: [student@gcet ~]$cc message_send.c
[student@gcet ~]$ mv a.out msgsend
[student@gcet ~]$ ./msgsend
msgget: Calling msgget(0x4d2,01666)
msgget: msgget succeeded: msqid = 0
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
27
msgget: msgget succeeded: msqid = 0
msgget: msgget succeeded: msqid = 0
Message: "Did you get this?" Sent
[student@gcet ~]$ cc message_rec.c
[student@gcet ~]$ mv a.out msgrec
[student@gcet ~]$./msgrec
Output: [1] 2907
[student@gcet ~]$ Did you get this?
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
28
Linux Programming No: 23 AIM: Write a C Program to allow cooperating processes to lock a resource for exclusive use,using a)Semaphores,b)Flock or lockf system calls. Program: #include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<unistd.h> int main(int argc,char* argv[]) { struct flock f1={f_wrlck,seek_set,0,0,0); int fd; f1.l_type=f_rdlck; if((fd=open(‘rr.txt”,o_rdwr))==-1) { perror(“open”); exit(1); } printf(“press<return> to try to get lock:”); getchar(); printf(“trying to get lock”): if(fnctl(fd,f_setlkw,&f1)==-1) { perror(“fcntl”); exit(1); } printf(“got lock \n”); printf(“press <return> to release lock:”); getchar( ); f1.l_type=f_unlck; if(fcntl(fd,f_setlk,&f1)==-1) { perror(“fcntl”); exit(1); } printf(“unlocked\n”); close(fd); } Output: press<return> to try to get lock
trying to get lock
press <return> to release lock unlocked
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
29
Linux Programming No: 24 AIM: Write a C program that illustrates suspending and resuming processes using signals Program: #include <stdio.h> #include <ospace/unix.h> int child_function() { while (true) // Loop forever. { Printf("Child loop\n"); os_this_process::sleep( 1 ); } return 0; // Will never execute. } int main() { os_unix_toolkit initialize; os_process child ( child function ); // Spawn child. os_this_process::sleep( 4 ); printf("child.suspend()\n"); child.suspend(); printf("Parent sleeps for 4 seconds\n"); os_this_process::sleep (4); printf("child.resume()"); child.resume (); os_this_process::sleep (4); printf("child.terminate()"); child.terminate (); printf("Parent finished"); return 0; } Output: Child loop
Child loop
Child loop
Child loop
Child loop
child.suspend()
Parent sleeps for 4 seconds
child.resume()
Child loop
Child loop
Child loop
Child loop
child.terminate()
Child loop
Parent finished
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
30
Linux Programming No: 25 AIM: Write a C program that implements a producer-consumer system with two processes.(Using Semaphores). Program: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #define NUM_LOOPS 20 int main(int argc, char* argv[]) { int sem_set_id; union semun sem_val; int child_pid; int i; struct sembuf sem_op; int rc; struct timespec delay; sem_set_id = semget(IPC_PRIVATE, 1, 0600); if (sem_set_id == -1) { perror("main: semget"); exit(1); } printf("semaphore set created, semaphore set id '%d'.\n", sem_set_id); sem_val.val = 0; rc = semctl(sem_set_id, 0, SETVAL, sem_val); child_pid = fork(); switch (child_pid) { case 1: perror("fork"); exit(1); case 0: for (i=0; i<NUM_LOOPS; i ) { sem_op.sem_num = 0; sem_op.sem_op = -1; sem_op.sem_flg = 0; semop(sem_set_id, &sem_op, 1); printf("consumer: '%d'\n", i); fflush(stdout); sleep(3); }
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
Siddhartha Institute of Engineering & Technology, IBP. LP Lab Record
40
Linux Programming No: 29 AIM: Write a C program that illustrates the creation of child process using fork system call. One process finds sum of even series and other process finds sum of odd series Program: #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> int main() { int i,n,sum=0; pid_t pid; system(“clear”); printf(“Enter n value:”); scanf(“%d”,&n) pid=fork(); if(pid==0) { printf(“From child process\n”); for(i=1;i<n;i+=2) { printf(“%d\”,i); sum+=i; } printf(“Odd sum:%d\n”,sum); } else { printf(“From process\n”); for(i=0;i<n;i+=2) { printf(“%d\”,i); sum+=i; } printf(“Even sum:%d\n”,sum); } }