Sie sind auf Seite 1von 37

VIGNAN UNIVERSITY, Vadlamudi

DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 1

SESSION 1:
A) LOG INTO THE SYSTEM:

$Enter User Name: MCAVU1 Enter Password: MCAVU001


B) USE VI EDITOR TO CREATE A FILE CALLED MYTEXT.TXT WHICH CONTAINS SOME TEXT:

STEP 1: STEP 2:

$VI mytext.txt and press I to enter into INSERT mode TYPE SOME TEXT AS FOLLOWS: reason

Welcome to UNIX, the open operating system. UNIX is found on virtually all computer hardware in use today. In fact, its very pervasiveness is most likely the you are starting to explore its capabilities. C) CORRECT TYPING ERRORS DURING CREATION:

Correct typing errors if any in the text by moving the cursor around the text. The following cursor movement commands help in moving the cursor around the file.

COMMAND h,backspace L,spacebar 0 $ k, j +,return


D) SAVE THE FILE:

FUNCTION Moves the cursor one character to the left Moves the cursor one character to the right Moves the cursor to the beginning of the current line Moves the cursor to the end of the current line Moves the cursor one line up Moves the cursor one line down Moves the cursor to the beginning of the previous line Moves the cursor to the beginning of the next line

Press ESC to exit the INSERT mode and enter into command mode. Now type : w and press enter to save the file. Type CTRL+Z to exit the VI editor. E) LOGOUT OF THE SYSTEM:

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 2

Type LOGOUT to exit the UNIX editor.

SESSION 2:

A) LOG INTO THE SYSTEM:


$Enter User Name: MCAVU1 Enter Password: MCAVU001 B) OPEN THE FILE CREATED IN SESSION 1: $ VI mytext.txt (Or) $ Cat mytext.txt C) ADD SOME TEXT: Press I to enter into the INSERT mode. Append some text as follows: Welcome to UNIX, the open operating system. UNIX is found on virtually all computer hardware in use today. In fact, its very pervasiveness is most likely the reason you are starting to explore its capabilities. This chapter introduces you to the UNIX environment. After providing a basic understanding of its environment, we show you how to access a UNIX system and present its basic structure and some common commands. Press ESC to exit the insert mode and type : q save the file and exit the VI editor. The following help us in adding text to a file.

COMMAND i I a A o O

FUNCTION Inserts text before the current character. Inserts text at the beginning of the current line. Appends text after the current character. Appends text at the end of the current line. Opens an empty text line for new text after the current line Opens an empty text line for new text before the current line

MAKE A DIRECTORY: The following is the command to make a directory. $mkdir unix COPYING A FILE: we use cp command to copy files.

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 $cp myfile.txt unix Page No: 3

MOVING A FILE: A file can be moved from one location to another using the mv command. $mv /home/mcavu6/unix/myfile.txt /home/mcavu6/lab The above command moves a file named myfile.txt from unix directory to lab directory. We use the same command to rename a file. LIST DIRECTORY: The list (ls) command lists the contents in a directory. Depending on the options used, it can list files, directories or subdirectories. F) SAVE THE CHANGES: Press ESC to exit the insert mode and type : q save the file and exit the VI editor. G) LOGOUT OF THE SYSTEM: Type LOGOUT to exit the UNIX editor.

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 4

SESSION:-3 Text Processing Commands


WC: (Word Count) This command gives us about word count of a given files. This also gives the count of characters and the lines in the given file: Syntax: Wc l file name -- gives us about lines count in the file Wc c filename -- gives us about characters count in a file Wc w filename -- gives us about words count in a files OD: Dump files in octal and other formats. Syntax: Od [option] [FILE]. Od [-abcdfilosx] [FILE] [[+]OFFSET[.][b]] Od traditional [option] [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]] This command writes an unambiguous representation, octal bytes by default, of FILE to standard output. With more than one FILE argument, concatenate them in the listed order to form the input. With no FILE, or when FILE is -, read standard output. SORT: Sorts the lines of the text file. Syntax: Sort [option] [file]. Write sorted concatenation of all FILES to standard output. -b : ignore leading blanks -d : consider only blanks and alphanumeric characters -f : fold lower case to upper case characters -n : compare according to string numerical value -R : sort by random hash of keys. TAIL:This command gives the last 10 lines in a given file Syntax: Tail filename Tail -1filename By executing above command it displays the last line of a given file

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 5

HEAD:This command displays first 10 lines in a file Syntax: Head filename Head -2 filename The above command gives first 2 lines in the given file. UNIQ: This command displays uniq lines of the given files. That is successive lines of a file are same then they will be removed. By default output will be on to the screen. This can also be used to removed the empty lines from a given file. The useful c option prefixes each line of the input file with its number of occurrences. Syntax: Uniq -c filename GREP: This command displays the lines containing the given search option. Syntax:Grep option filename. Here option means the words in the file name. DIFF:This is used to compare the contents of two files in general Syntax: Diff file1 file2. If the content of file1 and file2 is same it displays nothing. CMP: The cmp utility compares two files of any type and writes the results to the standard output. By default, cmp is silent if the files are same: if they differ, the byte and line number at which th first difference is occurred is reported. Syntax: Cmp file1 file2 COMM: Comm. compare two sorted files line by line Syntax: Comm file1 file2 CUT: This command displays the word in the line by giving the position of the character in each line. Syntax: Cut position filename Cut f1,3 filename This displays the 1 and 3rd word of each line in the filename.

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 6

PASTE: This is used to join the files vertically. Syntax: Paste file1 file2 > destination file. By opening the destination file using the cat command the result is displayed.

DISK & BACKUP UTILITIES


DF: This command displays details about the each of the mounted partition, percentage of free ness, percentage of occupation etc. DU: This command displays disk usage(usually in multiples of 1K BLOCKS). DU command without any argument displays disk usage of all files, subdirectories of current corking directory. Syntax: Du directoryname This displays disk usage of all files sub-directories of the given directory. WHO: This displays details about the user such as user name, terminal on which working and since when they are working. TAR: This command is used to join a group of files and prepare a archive file. Tar cvf a.tar directoryname or filename This command creates a archive file a.tar by joining the given file or files in the given directory. Tar cvZf a.tZ directoryname or filename This command creates compressed tar archive. Tar cvzf a.tgz directoryname or filename This command creates gzipped tar archive. Tar xvf a.tar This command extracts all files from the archive. Tar xvzf a.tz This command extracts all files from the compressed archive. Tar xvzf a.tgz This command extracts all files from the gzipped archive.

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 7

CPIO: This is also used for backup purpose. Normally this command requires list of filename asinput and the results archive file which appears on the standard output. Ls | cpio o > archivefilename The above command creates archive having all the files of current directory. Cpio I abc <archivefilename This command restores all the files from the archive file. Cpio I *.c <archivefilename This command restores all the files with extension c from the archivefile. We can create the archive on the tapes or other devices also. Find . ctime 2 print |cpio ov > /dev/rmt 0 This command creates backup file on magnetic tape rmt 0 and stores all the files which are created in the recent 2 days. PS: Report a snapshot of the current process. Syntax: Ps[option] Ps displays information about a selection of the active process. If you want to repetitive update of the selection and the displayed information, use top instead. This version of ps accepts several kinds of options:
1 2 3 Unix options, which may be grouped and must be preceded by a dash. Bsd options, which may be grouped and must not be used with a dash. Gnu long options, which are preceded by two dashes.

Options of different types may be freely mixed, but conflicts can appear. There are some synonymous options, which are functionally identical, due to the many standards and ps implementations that this ps is compatible with.

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 8

SESSION-4
1) WRITE A SHELL SCRIPT TO GENERATE A MULTIPLICATION

TABLE TO GENERATE MULTIPLICATION TABLE

Program: #To generate a multiplication table Echo, "Enter the number" Read n i=1 While [ $i -le 10 ] do r=`expr $n \* $i` echo $n x $i = $r i=`expr $i + 1` done

Out put :
[mca49@MCA ~]$ vi aaa1.sh [mca49@MCA ~]$ chmod u+x aaa1.sh [mca49@MCA ~]$ ./aaa1.sh enter the number 5 5x1=5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 9

2) WRITE A SHELL SCRIPT THAT COPIES MULTIPLE FILES IN A

DIRECTORY
Aim : to write a shell script that copies multiple files in a directory Program : #usage mul files <filename> echo "enter directory name into which files should be copied" read dirname for file in $* do cp $* $dirname done

Output : [mca49@MCA ~]$ vi unix3.sh [mca49@MCA ~]$ chmod u+x unix3.sh [mca49@MCA ~]$ ./unix3.sh [mca49@MCA ~]$ ./unix3.sh unix2.sh unix3.sh enter directory name into which files should be copied lab170908 [mca49@MCA ~]$ ls lab170908 unix2.sh unix3.sh

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 10

3) Write a shell script that counts the number of lines and words present

in a given program .
Aim: To write a shell program that copies multiple files to a directory Program: #to count the no of lines,words in a given file echo "enter a filename to count the lines and words" read filename echo "the no of lines in a given filename are" cat $filename |wc -l echo "the no of words in a given file are" cat $filename |wc w

Out put : [mca49@MCA ~]$ vi unix2.sh [mca49@MCA ~]$ chmod u+x unix2.sh [mca49@MCA ~]$ ./unix2.sh enter a filename to count the lines and words lab14.c the no of lines in a given filename are 37 the no of words in a given file are 108

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 11

4) Write a shell script that displays the list of all files in the given

directory
Aim: To display the list of files in the given directory Program: # to display the files in directory echo " enter the directory name " read dirname ls $dirname

Out put : [mca49@MCA ~]$ vi unix4.sh [mca49@MCA ~]$ chmod u+x unix4.sh [mca49@MCA ~]$ ./unix4.sh enter the directory name lab100908 [mca49@MCA ~]$ ls lab100908 [mca49@MCA ~]$ ./unix4.sh enter the directory name lab170908 unix2.sh unix3.sh

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 12

5) WRITE A SHELL SCRIPT THAT ADDS, SUBSTRACT,MULTIPLIES,

AND DIVIDES THE TWO GIVEN INTEGERS. THERE ARE TWO DIVISION OPTIONS : ONE RETURNS THE QUOTIENT AND THE OTHER RETURNS REMINDER. THE SCRIPT REQUIRES 3 ARGUMENTS : THE OPERATION TO BE USED AND TWO INTEGERS NUMBERS. THE OPTIONS ARE ADD(-A) , SUBSTRACT (-S) MULTIPLY (-M) , QUOTIENT(-C) AND REMAINDER(-R).
Aim : To perform Airthematic operations Program: #to perform artithematic operations echo "enter the two numbers" read a b echo "enter ur choice" echo "-a.addition" echo "-s.subtraction" echo "-m.multiplication" echo "-c .quotient" echo "-r remainder" read op case $op in -a ) r=`expr $a + $b` echo "the addition value is $r" ;; -s ) r=`expr $a - $b` echo "the subtraction value is $r" ;; -m ) r=`expr $a \* $b` echo "the multiplication value is $r" ;; -c ) r=`expr $a / $b` echo "the quotient is $r"

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 ;; -r ) r=`expr $a % $b` echo "the remainder is $r" ;; Page No: 13

*) echo "not a valid operator" ;; esac

Out put: [mca49@MCA ~]$ vi unix5.sh [mca49@MCA ~]$ chmod u+x unix5.sh [mca49@MCA ~]$ ./unix5.sh enter the two numbers 10 20 enter ur choice -a.addition -s.subtraction -m.multiplication -c .quotient -r remainder -a the addition value is 30 [mca49@MCA ~]$ ./unix5.sh enter the two numbers 10 20 enter ur choice -a.addition -s.subtraction -m.multiplication -c .quotient -r remainder -r the remainder is 10

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 14

6. WRITE A SHELL SCRIPT TO REVERSE THE ROWS AND COLUMNS

OF A MATRIX.
Aim: To reverse the rows and columns of a matrix Program : echo "enter the size of matrix:" read r read c echo "enter elements:" i=0 while [ $i -lt $r ] do j=0 while [ $j -lt $c ] do read a$i$j j=`expr $j + 1` done i=`expr $i + 1` done echo "the transpose of matrix is:" i=0 while [ $i -lt $c ] do j=0 while [ $j -lt $r ] do echo ""$[a$j$i] j=`expr $j + 1` done i=`expr $i + 1` done

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 15

Output: [mca49@MCA ~]$ vi unix6.sh [mca49@MCA ~]$ chmod u+x unix6.sh [mca49@MCA ~]$ ./unix6.sh enter the size of matrix: 2 2 enter elements: 1 2 3 4 the transpose of matrix is: 1 3 2 4

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 16

SESSION-5
7) IMPLEMENT IN C CAT UNIX COMMAND USING SYSTEM CALLS Aim : To implement cat command Program : #include<stdlib.h> #include<stdio.h> #include<fcntl.h> #include<unistd.h> #include<sys/stat.h> #include<sys/types.h> int main( int argc,char *argv[] ) { int f=0,n; char m[80]; struct stat s; if(argc!=2) { printf("mismatch argument"); exit(1); } if(access(argv[1],F_OK)) { printf("file exits"); exit(1); } if(stat(argv[1],&s)<0) { printf("stat error"); exit(1); } if(S_ISREG(s.st_mode)<0) { printf("not a regular file"); exit(1); }

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 if(geteuid()==s.st_uid) if(s.st_mode&S_IRUSR) f=1; else if(getegid()==s.st_gid) if(s.st_mode &S_IRGRP) f=1; else if(s.st_mode&S_IROTH) f=1; Page No: 17

if(!f) { printf("permission denied"); exit(1); } f=open(argv[1],O_RDONLY); while((n=read(f,m,80))>0) write(1,m,n); printf("\n"); }

Out put : [mca49@MCA ~]$ cc unix7.sh cc: unix7.sh: No such file or directory cc: no input files [mca49@MCA ~]$ cc unix7.c [mca49@MCA ~]$ ./a.out unix2.sh #to count the no of lines,words in a given file echo "enter a filename to count the lines and words" read filename echo "the no of lines in a given filename are" cat $filename |wc -l echo "the no of words in a given file are" cat $filename |wc -w

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 18

8) WRITE A C PROGRAM THAT ILLUSTRATES HOW TO EXECUTE TWO COMMANDS CONCURRENTLY WITH A COMMAND PIPE. Aim: To execute two commands concurrently with a command pipe Program: #include<stdio.h> #include<stdlib.h> #include<unistd.h> int main() { int pfds[2]; pipe(pfds); if(!fork()) { close(1); dup(pfds[1]); close(pfds[0]); execlp("ls","ls", NULL); } else { close(0); dup(pfds[0]); close(pfds[1]); execlp("wc","wc","-l", NULL); } }

output:
[mca36@MCA lab111108]$ ./a.out pipe.c 6

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 19

9) WRITE A C PROGRAM THAT ILLUSTRATES THE TWO WAY

COMMUNICATION WITH UNIDIRECTIONAL PIPLE.


Aim: To create two-way communication with unidirectional piple. Program: #include<stdlib.h> #include<stdio.h> #include<unistd.h> void do_child(int data_pipe[]) { int c; int rc; close(data_pipe[1]); while((rc=read(data_pipe[0],&c,1))>0) putchar(c); exit(0); } void do_parent(int data_pipe[]) { int c; int rc; close(data_pipe[0]); while((c=getchar())>0) { rc=write(data_pipe[1],&c,1); if(rc==-1) { printf("parent:write"); close(data_pipe[1]); exit(1); } } close(data_pipe[1]); exit(0); } int main(int argc, char *argv[]) { int data_pipe[2];

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 int pid; int rc; rc=pipe(data_pipe); Page No: 20

if(rc==-1) { printf("pipe"); exit(1); }

pid=fork(); switch (pid) { case -1: printf("fork"); exit(1); case 0: do_child(data_pipe); default: do_parent(data_pipe); } return 0; } output: [mca36@MCA lab111108]$ ./a.out twopipe.c this is unix lab this is unix lab ^Z [1]+ Stopped ./a.out twopipe.c

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 21

10) WRITE A C PROGRAM THAT ILLUSTRATES THE TWO-WAY

COMMUNICATION WITH BIDIRECTIONAL PIPE.


Aim: To create two way communication with bidirectional pipe. Program: #include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<ctype.h> int main(int argc,char *argv[]) { int user_to_translator[2]; int translator_to_user[2]; int pid; int rc; rc=pipe(user_to_translator); if(rc==-1) { printf("main:pipe user_to_translator"); exit(1); } rc=pipe(translator_to_user); if(rc==-1) { printf("main:pipe translator_to_user"); exit(1); } pid=fork(); switch(pid) { case -1: perror("main:fork"); exit(1); case 0: translator(user_to_translator,translator_to_user); default: user_handler(translator_to_user,user_to_translator); } return 0; }

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 void user_handler(int input_pipe[],int output_pipe[]) { int c,rc; char ch; close(input_pipe[1]); close(output_pipe[0]); Page No: 22

while((c=getchar())>0) { ch=(char)c; rc=write(output_pipe[1],&ch,1); if(rc==-1) { printf("user hadler:write"); close(input_pipe[0]); close(output_pipe[1]); exit(1); } rc=read(input_pipe[0],&ch,1); c=(int)ch; if(rc<=0) { printf("user hadler:read"); close(input_pipe[0]); close(output_pipe[1]); exit(1); } putchar(c); } close(input_pipe[0]); close(output_pipe[1]); exit(0); } void translator(int input_pipe[],int output_pipe[]) { int c; char ch; int rc; close(input_pipe[1]); close(output_pipe[0]); while(read(input_pipe[0],&ch,1)>0) { c=ch; if(isascii(c)&&isupper(c)) c=tolower(c); ch=c; rc=write(output_pipe[1],&ch,1);

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 if(rc==-1) { printf("translator:write"); close(input_pipe[0]); close(output_pipe[1]); exit(1); } } close(input_pipe[0]); close(output_pipe[1]); exit(0); } output: [mca36@MCA lab121108]$ ./a.out bipipe.c THIS IS UNIX LAB this is unix lab ^Z [2]+ Stopped ./a.out bipipe.c . Page No: 23

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 24

11) WRITE A C PROGRAM THAT ILLUSTRATES THE CREATION OF CHILD PROCESS USING FORK SYSTEM CALL. Aim: To write a c program that illustrates the creation of child process using fork system call Program : #include<sys/types.h> #include"ourhdr.h" #include<stdlib.h> #include<stdio.h> #include<unistd.h> int glob=6; char buf[]="a write to stdout\n"; int main(void) { int var; pid_t pid; var=88; if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1) printf("write error"); if((pid=fork())<0) { printf("fork error"); printf("before fork"); } else if(pid==0) { glob++; var++; } else sleep(2); printf("pid=%d,glob=%d,var=%d\n",getpid(),glob,var); } output: [mca36@MCA lab121108]$ ./a.out fork1.c a write to stdout pid=6981,glob=7,var=89

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 pid=6980,glob=6,var=88 Page No: 25

12) WRITE A C PROGRAM THAT DISPLAYS THE REAL TIME OF A DAY

EVERY 60 SECOND
Aim :To . Write a c program that displays the real time of a day every 60 second Program : #include<stdio.h> #include<time.h> int main() { int i=1; while(i<=10) { time_t now; time(&now); printf("current time is:%s",ctime(&now)); sleep(60); i++; } return 0; } output: [mca36@MCA lab121108]$ ./a.out time.c current time is:Tue Nov 25 11:30:05 2008

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 26

13) WRITE A C PROGRAM THAT ILLUSTRATES FILE LOCKING USING SEMAPHORES. Aim : To write a c program that illustrates file locking using semaphores. Program: /* Initialization of a semaphore */ #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<stdio.h> #define KEY (1492) void main() { int id; union semun { int val; struct semid *buf; ushort *array; }argument; argument.val=0; id=semget(KEY,1,0666|IPC_CREAT); if(id<0) { fprintf(stderr,"unable to obtain semaphore\n"); exit(0); } if(semctl(id,0,SETVAL,argument)<0) { fprintf(stderr,"cant set semaphore value \n"); } else { fprintf(stderr,"semaphore %d initialised\n",KEY); } }

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 27

output: [mca36@MCA lab181108]$ ./file semaphore 1492 initialised

b)

/* semaphore using v operations*/

#include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #define KEY (1492) void main() { int id; struct sembuf operations[1]; int retval; id=semget(KEY,1,0666); if(id<0) { fprintf(stderr,"program sem.c cannot find semaphore exiting \n"); exit(0); } printf("program sem.c about to do a v-operation \n"); operations[0].sem_num=0; operations[0].sem_op=1; operations[0].sem_flg=0; retval=semop(id,operations,1); if(retval==0) { printf("successful v-operations by program sem.c \n"); } else { printf("semd:v-operation did not succeed \n"); perror("reason"); } } output: [mca36@MCA lab181108]$ ./file1 program sem.c about to do a v-operation successful v-operations by program sem.c

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 28

C)

/* semaphore using p operations*/

#include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #define KEY (1492) void main() { int id; struct sembuf operations[1]; int retval; id=semget(KEY,1,0666); if(id<0) { fprintf(stderr,"program sem1.c cannot find semaphore exiting \n"); exit(0); } printf("program sem1.c about to do a p-operation \n"); printf("process id is %d \n",getpid()); operations[0].sem_num=0; operations[0].sem_op=-1; operations[0].sem_flg=0; retval=semop(id,operations,1); if(retval==0) { printf("successful p-operations by program sem1.c \n"); printf("process id is %d \n",getpid()); } else { printf("semd:p-operation did not succeed \n"); perror("reason"); } } output: [mca36@MCA lab181108]$ ./files program sem1.c about to do a p-operation

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 process id is 7519 successful p-operations by program sem1.c process id is 7519 Page No: 29

14) WRITE A C PROGRAM TO DEVELOP SIMPLE CLIENT AND SERVER

APPLICATION USING SOCKET (SYSTEM CALLS)


Aim: To . write a c program to develop simple client and server application using socket (system calls) Program: /* server */ #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<sys/un.h> #define SOCK_PATH "echo_socket" int main(void) { int s,t,len; struct sockaddr_un remote; char str[100]; if((s=socket(AF_UNIX,SOCK_STREAM,0))==-1) { printf("socket"); exit(1); } printf("trying to connect..\n"); remote.sun_family=AF_UNIX; strcpy(remote.sun_path,SOCK_PATH); len=strlen(remote.sun_path)+sizeof(remote.sun_family); if(connect(s,(struct sockaddr *)&remote,len)==-1) { printf("connect eror"); exit(1); } printf("connected.\n"); while(printf(">"),fgets(str,100,stdin),!feof(stdin))

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 { if(send(s,str,strlen(str),0)==-1) { printf("send error"); exit(1); } Page No: 30

if((t=recv(s,str,100,0))>0) { //str[1]='\0'; printf("echo>%s",str); } else { if(t<0) printf("recv error"); else printf("server closed connection\n"); exit(1); } } close(s); return 0; }

/* client */
#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<sys/un.h> #define SOCK_PATH "echo_socket" int main(void) { int s,s2,t,len; struct sockaddr_un local,remote; char str[100]; if((s=socket(AF_UNIX,SOCK_STREAM,0))==-1) {

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 printf("socket"); exit(1); } local.sun_family=AF_UNIX; strcpy(local.sun_path,SOCK_PATH); unlink(local.sun_path); len=strlen(local.sun_path)+sizeof(local.sun_family); if(bind(s,(struct sockaddr*)&local,len)==-1) { printf("bind error"); exit(1); } if(listen(s,5)==-1) { printf("listen"); exit(1); } for(;;) { int done,n; printf("waiting for a connection...\n"); t=sizeof(remote); if((s2=accept(s,(struct sockaddr*)&remote,&t))==-1) { printf("accept error"); exit(1); } printf("connected.\n"); done=0; do { n=recv(s2,str,100,0); if(n<=0) { if(n<0) printf("recv error"); done=1; } if(!done) if(send(s2,str,n,0)<0) { printf("send error"); done=1; Page No: 31

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA } }while(!done); close(s2); } return 0; } Regd.No: 101FD01001 Page No: 32

Out put: $ cc o echores echoc.c $./ echores Trying to connect. Connected .

$ cc o rep echos.c $ ./rep Waiting for a connection connected

> this is a program echo > this is a program > illustrating echo > illustrating >usage of echo > usage of >Sockets echo > Sockets

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 33

15). Write a c program that illustrates inter process communication

using shared memory


Aim: To Write a c program that illustrates inter process communication using shared memory Program,: #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/ipc.h> #include<sys/shm.h> #define SHM_SIZE 1024 int main(int argc,char *argv[]) { key_t key; int shmid; char *data; int mode; if(argc>2) { fprintf(stderr,"usage:shmdemo(data_to_write)\n"); exit(1); } if((key=ftok("share.c",'r'))==-1) { printf("ftok"); exit(1); } if((shmid=shmget(key,SHM_SIZE,0644)IPC_CREAT)==-1) { printf("shmget"); exit(1); } data=shmat(shmid,(void *),0,0); if(data==(char)*(-1)) { printf("shmat"); exit(1);

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 } if(argc==2) { printf("writing to segment:\%s\n",argv[1]); strcpy(dat,argv[1],SHM_SIZE); } else Page No: 34

printf("segment contains:\%s\n",data); if(shmdt(data)==-1) { perror("shmdt"); exit(1); } return 0; } Out put : ./a.out unix Writing to segment : unix

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 Page No: 35

16) WRITE A C PROGRAM THAT ILLUSTRATES THE FOLLOWING

A) CREATING A MESSAGE QUEUE B) WRITING TO A MESSAGE QUEUE C) READING FROM MESSAGE QUEUE
Aim: To . Write a c program that illustrates the following a) Creating a message queue b) Writing to a message queue c ) Reading from message queue Program : #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<sys/types.h> #include<sys/msg.h> struct msg_msgbuf { long mtype; char mtext[200]; }; int main(void) { struct msg_msgbuf buf; int msgid; key_t key; if((key=ftok("msg1.c",'b'))==-1) { printf("ftok"); exit(1); } if((msgid=msgget(key,0644|IPC_CREAT))==-1) { printf("msgget"); exit(1); } printf("enter lines of text and to quit:\n"); buf.mtype=1;

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 while(gets(buf.mtext),!feof(stdin)) { if(msgsnd(msgid,(struct msgbuf*)&buf,sizeof(buf),0)==-1) printf("msgsnd"); } if(msgctl(msgid,IPC_RMID,NULL)==-1) { printf("msgctl"); exit(1); } return 0; } output: [mca36@MCA lab181108]$ ./mm enter lines of text and to quit: this is unix lab programming^Z [3]+ Stopped ./mm b) #include<stdio.h> #include<stdlib.h> #include<errno.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> struct msg_msgbuf { long mtype; char mtext[200]; }; int main(void) { struct msg_msgbuf buf; int msgid; key_t key; if((key=ftok("msg1.c",'b'))==-1) { printf("ftok"); exit(1); } if((msgid=msgget(key,0644))==-1) { perror("msgget"); exit(1); } Page No: 36

VIGNAN UNIVERSITY, Vadlamudi


DEPARTMENT OF MCA Class: II MCA Regd.No: 101FD01001 printf("spock:ready to receive messages,obtain \n"); for(;;) { if(msgrcv(msgid,(struct msgbuf *)&buf,sizeof(buf),0,0)==-1) { perror("msgrcv"); exit(1); } printf("spock:\"%s\"\n",buf.mtext); } return 0;} output: [mca36@MCA lab181108]$ ./mmm spock:ready to receive messages,obtain spock:"this is unix lab" spock:programming Page No: 37

Das könnte Ihnen auch gefallen