Upload
naveen-kumar
View
22
Download
3
Embed Size (px)
Citation preview
Regd.No: 101FD01001 Page No: 1 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
SESSION 1 :
A) LOG INTO THE SYSTEM:
$Enter User Name: MCAVU1Enter Password: MCAVU001
B) USE VI EDITOR TO CREATE A FILE CALLED MYTEXT.TXT WHICH CONTAINS SOME TEXT:
STEP 1: $VI mytext.txt and press ‘I’ to enter into INSERT mode
STEP 2: TYPE 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.
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 FUNCTIONh,backspace Moves the cursor one character to the leftL,spacebar Moves the cursor one character to the right
0 Moves the cursor to the beginning of the current line
$ Moves the cursor to the end of the current linek, Moves the cursor one line upj Moves the cursor one line down- Moves the cursor to the beginning of the previous
line+,return Moves the cursor to the beginning of the next line
D) SAVE THE FILE:
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:
Regd.No: 101FD01001 Page No: 2 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
Type ’LOGOUT’ to exit the UNIX editor.
SESSION 2:A) LOG INTO THE SYSTEM:
$Enter User Name: MCAVU1Enter 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 FUNCTIONi Inserts text before the current character.I Inserts text at the beginning of the current line.a Appends text after the current character.A Appends text at the end of the current line.o Opens an empty text line for new text after the
current lineO 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 unixCOPYING A FILE: we use ‘cp’ command to copy files.
Regd.No: 101FD01001 Page No: 3 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
$cp myfile.txt unix
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/labThe 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.
Regd.No: 101FD01001 Page No: 4 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 fileWc –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 filenameTail -1filename
By executing above command it displays the last line of a given file
Regd.No: 101FD01001 Page No: 5 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
HEAD:-This command displays first 10 lines in a file
Syntax:Head filenameHead -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 filenameGREP: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 filenameCut –f1,3 filename
This displays the 1 and 3rd word of each line in the filename.
Regd.No: 101FD01001 Page No: 6 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 filenameThis 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 filenameThis command creates gzipped tar archive.
Tar –xvf a.tarThis command extracts all files from the archive.
Tar –xvzf a.tzThis command extracts all files from the compressed archive.
Tar –xvzf a.tgz
Regd.No: 101FD01001 Page No: 7 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
This command extracts all files from the gzipped archive.
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 > archivefilenameThe above command creates archive having all the files of current directory.
Cpio –I abc <archivefilenameThis command restores all the files from the archive file.
Cpio –I “”*.c <archivefilenameThis 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 Unix options, which may be grouped and must be preceded by a dash.2 Bsd options, which may be grouped and must not be used with a dash.3 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.
Regd.No: 101FD01001 Page No: 8 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
SESSION-4
1) WRITE A SHELL SCRIPT TO GENERATE A MULTIPLICATION TABLE TO GENERATE MULTIPLICATION TABLE
Program:
#To generate a multiplication tableEcho, "Enter the number"Read ni=1While [ $i -le 10 ]dor=`expr $n \* $i`echo $n x $i = $ri=`expr $i + 1`done
Out put :
[mca49@MCA ~]$ vi aaa1.sh[mca49@MCA ~]$ chmod u+x aaa1.sh [mca49@MCA ~]$ ./aaa1.shenter the number55 x 1 = 55 x 2 = 105 x 3 = 155 x 4 = 205 x 5 = 255 x 6 = 305 x 7 = 355 x 8 = 405 x 9 = 455 x 10 = 50
Regd.No: 101FD01001 Page No: 9 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 dirnamefor file in $*docp $* $dirnamedone
Output :
[mca49@MCA ~]$ vi unix3.sh[mca49@MCA ~]$ chmod u+x unix3.sh[mca49@MCA ~]$ ./unix3.sh [mca49@MCA ~]$ ./unix3.sh unix2.sh unix3.shenter directory name into which files should be copiedlab170908[mca49@MCA ~]$ ls lab170908unix2.sh unix3.sh
Regd.No: 101FD01001 Page No: 10 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 fileecho "enter a filename to count the lines and words"read filenameecho "the no of lines in a given filename are"cat $filename |wc -lecho "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.shenter a filename to count the lines and wordslab14.cthe no of lines in a given filename are37the no of words in a given file are108
Regd.No: 101FD01001 Page No: 11 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 directoryecho " enter the directory name "read dirnamels $dirname
Out put :
[mca49@MCA ~]$ vi unix4.sh[mca49@MCA ~]$ chmod u+x unix4.sh[mca49@MCA ~]$ ./unix4.sh enter the directory namelab100908[mca49@MCA ~]$ ls lab100908[mca49@MCA ~]$ ./unix4.sh enter the directory namelab170908unix2.sh unix3.sh
Regd.No: 101FD01001 Page No: 12 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 operationsecho "enter the two numbers"read a becho "enter ur choice"echo "-a.addition"echo "-s.subtraction"echo "-m.multiplication"echo "-c .quotient"echo "-r remainder"read opcase $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"
Regd.No: 101FD01001 Page No: 13 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
;;-r ) r=`expr $a % $b` echo "the remainder is $r" ;;
*) echo "not a valid operator" ;;
esac
Out put:
[mca49@MCA ~]$ vi unix5.sh [mca49@MCA ~]$ chmod u+x unix5.sh[mca49@MCA ~]$ ./unix5.shenter the two numbers10 20enter ur choice-a.addition-s.subtraction-m.multiplication-c .quotient-r remainder-athe addition value is 30[mca49@MCA ~]$ ./unix5.shenter the two numbers10 20enter ur choice-a.addition-s.subtraction-m.multiplication-c .quotient-r remainder-rthe remainder is 10
Regd.No: 101FD01001 Page No: 14 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 rread cecho "enter elements:"i=0while [ $i -lt $r ]doj=0while [ $j -lt $c ]doread a$i$jj=`expr $j + 1`donei=`expr $i + 1`doneecho "the transpose of matrix is:"i=0while [ $i -lt $c ]doj=0while [ $j -lt $r ]doecho ""$[a$j$i]j=`expr $j + 1`donei=`expr $i + 1`done
Regd.No: 101FD01001 Page No: 15 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
Output:
[mca49@MCA ~]$ vi unix6.sh[mca49@MCA ~]$ chmod u+x unix6.sh[mca49@MCA ~]$ ./unix6.shenter the size of matrix:22enter elements:1234the transpose of matrix is:1324
Regd.No: 101FD01001 Page No: 16 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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);
Regd.No: 101FD01001 Page No: 17 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
}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;
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.shcc: unix7.sh: No such file or directorycc: no input files[mca49@MCA ~]$ cc unix7.c[mca49@MCA ~]$ ./a.out unix2.sh#to count the no of lines,words in a given fileecho "enter a filename to count the lines and words"read filenameecho "the no of lines in a given filename are"cat $filename |wc -lecho "the no of words in a given file are"cat $filename |wc -w
Regd.No: 101FD01001 Page No: 18 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 pipeProgram:#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.c6
Regd.No: 101FD01001 Page No: 19 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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[]){
Regd.No: 101FD01001 Page No: 20 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
int data_pipe[2]; int pid; int rc; rc=pipe(data_pipe);
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.cthis is unix labthis is unix lab^Z[1]+ Stopped ./a.out twopipe.c
Regd.No: 101FD01001 Page No: 21 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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;
Regd.No: 101FD01001 Page No: 22 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
}void user_handler(int input_pipe[],int output_pipe[]){ int c,rc;char ch; close(input_pipe[1]); close(output_pipe[0]);
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;
Regd.No: 101FD01001 Page No: 23 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
rc=write(output_pipe[1],&ch,1);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.cTHIS IS UNIX LABthis is unix lab^Z[2]+ Stopped ./a.out bipipe.c.
Regd.No: 101FD01001 Page No: 24 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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.ca write to stdout
Regd.No: 101FD01001 Page No: 25 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
pid=6981,glob=7,var=89pid=6980,glob=6,var=88
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.ccurrent time is:Tue Nov 25 11:30:05 2008
Regd.No: 101FD01001 Page No: 26 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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); }
Regd.No: 101FD01001 Page No: 27 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
}
output:[mca36@MCA lab181108]$ ./filesemaphore 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]$ ./file1program sem.c about to do a v-operationsuccessful v-operations by program sem.c
Regd.No: 101FD01001 Page No: 28 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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
Regd.No: 101FD01001 Page No: 29 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
program sem1.c about to do a p-operationprocess id is 7519successful p-operations by program sem1.cprocess id is 7519
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");
Regd.No: 101FD01001 Page No: 30 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
while(printf(">"),fgets(str,100,stdin),!feof(stdin)){if(send(s,str,strlen(str),0)==-1){printf("send error");exit(1);}
if((t=recv(s,str,100,0))>0){
//str[1]='\0';
printf("echo>%s",str);}else{if(t<0)printf("recv error");elseprintf("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)
Regd.No: 101FD01001 Page No: 31 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
{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");
Regd.No: 101FD01001 Page No: 32 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
done=1;}}while(!done);close(s2);}return 0;}
Out put: $ cc –o echores echoc.c $ cc –o rep echos.c$./ echores $ ./rep Waiting for a connectionTrying to connect…. connectedConnected .
> this is a program echo > this is a program > illustratingecho > illustrating>usage of echo > usage of >Socketsecho > Sockets
Regd.No: 101FD01001 Page No: 33 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
15). Write a c program that illustrates inter process communication using shared memoryAim: 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 1024int 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");
Regd.No: 101FD01001 Page No: 34 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
exit(1); } if(argc==2) { printf("writing to segment:\%s\n",argv[1]); strcpy(dat,argv[1],SHM_SIZE); } else
printf("segment contains:\%s\n",data); if(shmdt(data)==-1) { perror("shmdt"); exit(1); } return 0;}
Out put :./a.out unixWriting to segment : unix
Regd.No: 101FD01001 Page No: 35 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
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 queueProgram :
#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");
Regd.No: 101FD01001 Page No: 36 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
buf.mtype=1; 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]$ ./mmenter lines of text and to quit:this is unix labprogramming^Z[3]+ Stopped ./mmb)#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);
Regd.No: 101FD01001 Page No: 37 Class: II MCA
VIGNAN UNIVERSITY, VadlamudiDEPARTMENT OF MCA
} 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]$ ./mmmspock:ready to receive messages,obtainspock:"this is unix lab"spock:”programming”