You are on page 1of 92

LINUX LAB PROGRAMS

1.Displaying all lines between specified line numbers


Aim: a shell script that accepts a file name, starting and ending line numbers as arguments
and displays all the lines between the given line numbers.
Algorithm:

1. Start
2. Get file name as first argument
3. Get starting ending line numbers as second & third arguments
4. Display the lines from starting line number t ending line number in specified
file using ‘sed’ command
5. Stop

Input:

$cat>file.dat
This is first shell program
For displaying
The lines between
The given numbers
Shell script:
Vi f1.sh
Sed –n “$2,$3’p’ $1
Execution:
$sh f1.sh emp.lst 2 4
Output:
For displaying
The lines between
The given numbers
Conclusion: the shell script is successfully executed for displaying specified lines in a file.

1
2.Deleting a word from list of files
Aim: Write a shell script that deletes all lines containing a specified word in one or more files
supplied as arguments to it.
Algorithm:

1. Start
2. Get the file names as command line arguments
3. Write “Enter the word to search & delete:”
4. Read word
5. For each argument repeat step 6 to step 8
6. If it is file then go to next step else display “error in file”
7. Search the lines not contain specified ‘word’
8. Write the above result into same file
9. Stop

Input:
$cat >a.txt
Hi
Hello
How are you
$cat >b.txt
Hello
Where are you
Bye
Shell script:
$vi f2.sh
echo “Enter word to search and delete:”
read word
while[ $# -gt 0]
do
if[ -f $l ]
then
grep –v $word $1|cat >$l
else
2
echo “error in file $l”
fi
shift l
done
Execution:
$sh f2.sh a.txt b.txt
Enter the word to search and delete:hello
Output:
$cat a.txt
Hi
How are you
$cat b.txt
Where are you
Bye
Conclusion: the awk script is successfully exectuted for is deleting specified word in a list of
files.

3
3.Displaying read,write and executable files
Aim: write a shell script that displays a list of all the files in the current directory to which the
user has read, write and execute permissions.
Algorithm

1. Start
2. For each file in current directory repeat step 3 to step.5
3. Check it is readable
4. Check it is writeable
5. Check it is executable
6. If it satisfies the steps 3,4,5 then display file name else skip the file.
7. Stop

Input: $ls –l
-rwxrwxrwx 1 root root 0 Nov 17 17:38 a.txt
-rwxrwx-----1 root root 0 Nov 17 17:39 b.txt
-r---------1 root root 0 Nov 17 17:40 c.txt
Drwx----1 root root 0 Nov 18 17:46 sub
Shell script:
Vi f3.sh
echo “the read,write,execution files are:”
for file in *
do
if [ -r $file ]
then
if [ -w $file ]
then
if [ -x $file ]
then
echo “$file”
fi
fi
fi
done
4
Execution:
$sh f3.sh
Output:
The read,write,execution files are:
a.txt b.txt sub
Conclusion: the shell script is successfully executed for is displaying read, write,execution files
in a directory.

5
4.finding file or directory
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
file, the number of lines on it is also reported.
Algorithm:

1. Start
2. Read file names as command line arguments
3. For each argument do step.5 to step.7
4. If given argument is a directory name then display “it is directory.”
5. If given argument is a ordinary file name then display “it is file”
6. If given argument is ordinary file then count number of lines in file
7. Display the count in the screen
8. Stop

Input:
$touch l.txt
$cat >m.txt
This
Linux
Shell program.
$mkdir sub
Shell script:
$vi f4.sh
While [ $# - gt 0 ]
Do
If [-f $1]
then
echo “$1 is file,contains ‘cat $1|wc –l’ lines.”
elif [ -d $list ]
then
echo “$1 is directory.”
fi
shift 1
6
done
Execution
$sh f4.sh l.txt m.txt sub
Output:
l.txt is a file contains 0 lines.
m.txt is a file contains 3 lines.
Sub is a directory.
Conclusion: the shell script is successfully executed for displaying file or directory in list of
arguments

7
5.number of occurrences of each word in list of files
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.
Algorithm:

1. Start
2. Get list of file names from command arguments
3. Get a word from first file
4. If the word is end of file then goto step.8 else go to next step
5. Count the occurrences of ‘word’ in each file.
6. Display the count for each file
7. Go to step.3
8. Stop

Input:
$cat >list1
mango
banana
pineapple
$cat >list2
mango
banana
$cat >list3
mango
mango
pineapple
shell script:
$vi f5.sh
file1=$1
shift 1
exec<$file1
while read li
do
echo “$lli:”
8
grep –c “$li” $@
done
execution:
sh f5.sh list1 list2 list3
output:
mango:
list2:1
list3:2
banana:
list2:1
list3:0
pineapple:
list2:0
list3:1
Conclusion: the shell script is successfully executed for displaying count of each word in
specified files.

9
6.Listing directories
Aim: write a shell script to list all of the directory files in adirectory.
Algorithm:
1. Start
2. Write “the directories files in current directory are:”
3. For each file in current directory do the step.4
4. Check it is directory or not, if it is directory then print file name
5. Stop.
Input:
$touch a.txt b.txt
$mkdir sub1 sub2
$ls
a.txt b.txt sub1 sub2
shell script:
Vi f6.sh
echo “the directorys are:”
for file in *
do
if [ -d $file ]
then
echo “$file”
fi
done
Execution:
$sh f6.sh
Output:
The directorys are:
Sub1
Sub2
Conclusion: the shell script is successfully executed for displaying directories in directory

10
7.Factorial of a number
Aim: write a shell script to find factorial of a given integer.
Algorithm:
1. Start
2. Write “enter the number:”
3. Read n
4. Fact <- 1
5. i <- 1
6. If i is less then or equals to n go to next step else go to step.9
7. f <- f * i
8. Go to step.6 by incrementing I by 1.
9. Write “the factorial of n is:”
10.Display ‘fact’ value
11.Stop
Shell script:
$vi f7.sh
echo “enter the number:”
read num
facat=1
while [ $num –gt 1]
do
f=’expr $fact\* $num’;
num=$((num-1));
done
echo “the factorial of $num is:$fact”
execution:
$sh f7.sh
Output:
Enter the number:
5
The factorial of 5 is: 120
Conclusion: the shell script is successfully executed for finding factorial of a given number.

11
8.Number of lines without vowels:
Aim: write an awk script to count the number of lines in a file that do not contain vowels.
Algorithm:
1.start
2.get the source file name
3. write “the number of lines not contain vowels are:”
4. k<- 0
5. For each row in the source file repeat the step.5 to step.7 until end of the file
6.check the row contain ‘a’ or ‘e’ or ‘i’ or ‘o’ or ‘u’
7. if the row not contain above characters then increment the c value by 1.
8. print the ‘k’ value
9.stop.
Input:
$cat >list.txt
Cat bat rat
Fly
Sky
Round the world
Awk script:
$vi f8.awk
BEGIN{
printf “the no of lines not contain vowels are:”
}!/[aA] | [eE] | [Li] | [Oo] | [Uu]/{
K++
}
END{
printf “%d”,k
}
Execution:
$awk –f f8.awk list.txt
Output:
The no of lines not contain vowels are:2
Conclusion: the awk script is successfully executed for displaying lines not containing vowels.
12
9.counting characters,words,lines
Aim: write an awk script to find the number of characters, words and lines in a file.
Algorithm:
1.start
2.get the source file name
3.set field separator as “ “ (space)
4.declare c<- 0, w<- 0, l<- 0
5.for each row in source file repeat the step.5 to step.7 until end of file
6.c <- c + length of row
7.w <- w + number of fields in row
8.increment the l by 1
9.print “characters:”, c value
10.print “word:”, w value
11.print “lines:”, l value
12.stop.
Input:
Cat>list2.txt
Hi how
Are
You
What are you
Doing bye
Awk script:
$vi f9.awk
BEGIN{
FS=” “
}{
c=c+length()
W=w+NF
l++
}
END{
13
printf “characters:%d\nwords:%d\nlines%d:”,c,w,l}
Execution:
$awk –f f9.awk list2.txt
Output:
Characters:29
Words:9
Line:5
Conclusion: the awk script is successfully executed for counting line,words,and characters in a file.

14
10.copying file using system calls and standard I/O:
Aim: write a c program that makes a copy of a file using standard I/O and system calls.
Algorithm:
1.start
2.declare src[10],dest[10],ch[2] as strings
3.display “enter the src file name:”
4.read src
5.display “enter the destination file name:”

6.read dest
7.open ‘src’ file in read mode
8.open ‘dest’ file in write or create ‘dest’ file.
9.display “src contains:”
10.get the character from src file and store it in ch
11.if it is end of file go to step.14 else go to next step
12.write ch into dest file
13.display the ch in the screen.
14.display ‘file is copied”
15.stop
Using standard I/O;
C source code:
$vi f10.c
#include<stdio.h>
#include<stdlib.h>
Int main()
{
Char src[10],dest[10],ch;
FILE *fp1,*fp2;
printf(“enter the source file name:”);
scanf(“%s”,src);
if((fp1=fopen(src,”r”))==0)
{
printf(“error in opening src file”);

15
exit(0);
}
printf(“enter the destination file name:”);
scanf(“%s”,dest);
if(fp2=fopen(dest,”w”))==0)
{
printf(“error in destination file”);
exit(1);
}
printf(“%s contain:\n”,src);
while((ch=getc(fp1))!=EOF){
fputc(ch,fp2);
printf(“%c”,ch);}
printf(“file is copied.”);
fclose(fp1);
fclose(fp2);
return 1;
}
Input:
$cat >abc.txt
Java is a simple, object oriented and multithreaded.
Execution:
Gcc f10.c -0 f10
$./f10
Output:
Enter the source file name:abc.txt
Enter the destination file name:abccpy.txt
Abc.txt contains:
Java is a simple, object oriented and multithreaded
File is copied.
Verification:
$cat abccpy.txt
Java is a simple, onject oriented and multithreaded.$
16
Using system call:
C source code:
$vi f10b.c
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#inclulde<unistd.h>
Int main()
{
Char src[10],dest[10],ch[2];
Int fd1,fd2,c;
printf(“enter the source file name:”);
scanf(“%s”,src);
if(fd1=open(src,O_RDONLY))==-1)
{
printf(“error in opening src file”);
exit(0);
}
printf(“enter the destination file:”);
scanf(“%s”,dest);
if((fd2=open(dest,O_CREAT|O_WRONLY,0700))==-1)
{
printf(“error in destination file”);
exit(0);
}
printf(“%s contains:\n”,src);
while(read(fd1,ch,1)==1)
{
write(1,ch,1);
write(fd2,ch,1);
}
printf(“file is copied”);
close(fd1);
17
close(fd2);
return 1;
}
Input:
$cat>def.txt
Cpp is a object oriented language
Execution:
$gcc f10b.c –o f10b
$./f10b
Output:
Enter the source file name:def.txt
Enter the destination file name:defcpy.txt
Def.txt contains:
Cpp is a object oriented language
File is copied
Verification:
$cat defcpy.txt
Cpp is a object oriented language
Conclusion: a c program is successfully executed for copying file using system calls and
standard I/O

18
11.IMPLEMENTING ‘CAT’ COMMAND:
Aim: to implement a c program to ‘cat’ unix command using system call.
Algorithm:
1.start
2.read the file name as first argument.
3.read the character from the given file.
4.display the character in the screen.
5.read the next character from file
6.if it is not end of file the goto step 4 else goto next step
7.stop
Source code:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
Int main(int argc,char **argv)
{
char ch[2];
int fd;
fd=open(argdv[1],O_RDONLY);
while((read(fd,ch,1))==1)
{
write(1,ch,1);
}
close(fd);
return 1;
}
Execution:
$gcc display.c –o display
$./display a.txt
Eno ename job salary dob
101 john sales 10000 12/10/89
103 pavan sales 2000 15/11/89

19
Output:
student@ubuntu:~$gcc –o prgcat.out prgcat.c
student@ubuntu:~$cat > ff
hello
hai
student@ubuntu:~$./prgcat.out ff
hello
hai
Conclusion: a c program is successfully executed for ‘cat’ unix command using system call.

20
11.b).IMPLEMETING ‘mv’COMMAND:-
Aim: To implement a c program to ‘mv’ unix command using system call
Algorithm:
1.start
2.decalre directory pointer dp
3.decalre an instance of structure dirent as dirp
4.declare p as string variable
5.if number of arguments ==1 then p,<-‘.’else p<-second argument
6.open directory p
7.read the file name
8.display the “file name”
9.read next file name
10.if not null then goto step 7else goto next step
11.stop
Source Code:
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[] )
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
21
}
Output:
student@ubuntu:~$gcc –o mvp.out mvp.c
student@ubuntu:~$cat > ff
hello
hai
student@ubuntu:~$./mvp.out ff ff1
student@ubuntu:~$cat ff
cat:ff:No such file or directory
student@ubuntu:~$cat ff1
hello
hai
Conclusion: the is command is successfully implemented inc.

22
12. Write a C program to emulate the Unix ls -1 command.
Aim: to implement C program to emulate the Unix ls -1 command
Source code:
#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
printf(“\nFork failed\n”);
exit (-1);
}
else if ( pid == 0 )
{ //child
execlp ( “/bin/ls”, “ls”, “-l”, NULL ); //execute ls
}
else
{ //parent
wait (NULL); //wait for child
printf(“\nchild complete\n”);
exit (0);
}
}

23
Output:
guest-glcbIs@ubuntu:~$gcc –o lsc.out lsc.c
guest-glcbIs@ubuntu:~$./lsc.out
total 100
-rwxrwx—x 1 guest-glcbls guest-glcbls 140 2012-07-06 14:55 f1
drwxrwxr-x 4 guest-glcbls guest-glcbls 140 2012-07-06 14:40 dir1
child complete
Conclusion:
C program successfully executed using system calls

24
13.Listing inode,File Name
Aim: To write a c program to list for ever file in a directory its inode number and file name
Algorithm:
1.start
2.declare directory pointer dp
3.declare an instance of structure dirent as dirp
4.declare struct start instance as buf
5.write “file_name,inode”
6.open the directory
7.read the file name
8.extract file information into buf
9.dispaly the “file name “and it’s inode number
10.using buf varable
11.read next file varable
12.stop
source code:
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>
#include<dirent.h.
int main(int argc,char**argv)
{
DIR*dp;
struct stat buf;
ino_t ino;
struct dirent*dirp;
if(argc!=2)
{
printf(“usage :dirname”);
exit(1);
}
if((dp=opendir(argv[1]))==NULL)
25
perror(“open:”);
printf(“\nfile_name inode”);
printf((“\n………..”);
while((dirp=readdir(dp))!=NULL)
{
stat(dirp->d_name,&buf);
ino=buf.st_ino;
printf(“\n%ld%s”,ino,dirp->d_name);
}
return 1;
}
Execution :
$gcc ilist.c-o ilist
$./ilist sub1
file_name inode
……………….
8781826 …
8781821 sub3
8781827 sub2
8781823 d.tct
8781935 a.txt
8781932
Output:
student@ubuntu:~$ mkdir dd
student@ubuntu:~$ cd dd
student@ubuntu:~/dd$ cat >f1
hello
^z
student@ubuntu:~/dd$ cd
student@ubuntu:~$gcc –o flist.out flist.c
student@ubuntu:~$./flist.out dd
hello
Conclusion: a c program is successfully executed for list file name its inode number.
26
14.redirects standard output to a file
Aim: to implement c programs that redirects standard output to a file
Source code:
#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:
student@ubuntu:~$ gcc –o std.out std.c
student@ubuntu:~$ls
downloads documents listing.c listing.out std.c std.out
student@ubuntu:~$ cat > f1
student@ubuntu:~$./std.out f1
student@ubuntu:~$cat f1
downloads
documents
listing.c
listing.out
std.c
std.out
27
15.CREATING CHILD PROCESS
Aim: T write a c program create a child process and allow the parent to display “parent”and
child to display”child”.
Algorithm:
1.start
2.Declare pid as pid_t data type
3.call fork() and pidreturn value of fork()
4.if pid<o then display “child procces creation error”
5.if pid==0 then display “child”
6.if pid>0 then display “parent”
7.stop.
Source code:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
pid=fork();
If(pid<o)
{
perror(“error in fork”);
}
if(pid==0)
{
printf(“/nchild procces:”);
}
if(pid>0)
{
printf(“\n parent process..”);
}
}

28
Execution:
$gcc child.c –o child
$/child
Child
Parent
Output:
student@ubutnu:$gcc –o child.out child.c
student@ubutnu: ./child.out
Hello World!
I am the child process.
I am the parent process

Conclusion : A c program is successfully excuted to display child process as”child”parent


process as “parent”

29
16.Zomble Process
Aim : To write a C program to create a zomble process
Algorithm:
1.start
2.declare pid as pid_t data type
3.call fork function and pid return value of fork()
5.sleep parent process
6.stop
source code:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
if(fork()>0)
{
printf(“parent with %d”,getpid());
sleep(10);
}
}
Execution:
$gcc zombie.c –o zombie
$./zombie&
$ps Z
LABEL PID TTY STST TIME COMMAND
user_u:system_r:unconfined_t 3769 pts/1 Ss 0:00 bash
user_u:system_r:unconfined_t 3799 pts/1 Ss 0:00 ./zom
user_u:system_r:unconfined_t 38009 pts/1 Ss 0:00 [zom]<defunct>
user_u:system_r:unconfined_t 3769 pts/1 Ss 0:00 ps Z
$ parent with 3799

30
Output:
guest-glcbIs@ubuntu:~$gcc zombie.c
guest-glcbIs@ubuntu:~$./a.out
Then command prompt will wait for some time(60 sec) and then again command prompt will
appear later.
Conclusion: A c program is successfully executed to create zombie process.

31
17.Orphan Process
Aim: To write a c program to illustrates a orphan process
Algorithm:
1.start
2.decalre pid as pid_t data type
3.call fork() and pid<- return value of fork()
4.if pid==0 then display “child process ..”
5.display parent process id and child process id
6.call sleep() to display “parent process”
7.if pid==1 then display the process
8.terminate parent the process
9.terminate the child after the sleep function
10.stop
Source code:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
pid=fork();
if(pid==0)
{
printf(“child process..”);
printf(“process id =%d,parented=%d”,getpid(),getppid());
sleep(15);
printf(“termination of child”);
}
if(pid>0)
{
printf(“parent process:%d”,getpid());
printf(“termination of parent,”);
32
}
}
Execution :
$gcc orphan.c-o orphan
$./orphan
Parent process:3395
Termination of parent
Child process..
Child id:3396 parent id:3395
Termination of child….
Output:
guest-glcbIs@ubuntu:~$gcc –o prg18.out prg18.c
guest-glcbIs@ubuntu:~$./prg18.out
I am the original process with PID2242 and PPID1677.
I am the parent with PID2242 and PPID1677
My child’s PID is 2243
PID2243 terminates.
$ I am the child with PID2243 and PPID1.
PID2243 termanates.

Conclusion : The creation of orphan process is successfully executed

33
18.Execute two commands concurrently with a command pipe.
Aim: to implement C program illustrates how to execute two commands concurrently with a
command pipe.
Source code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
int pfds[2];
char buf[30];
if(pipe(pfds)==-1)
{
perror("pipe failed");
exit(1);
}
if(!fork())
{
close(1);
dup(pfds[1];
system (“ls –l”);
}
else
{
printf("parent reading from pipe \n");
while(read(pfds[0],buf,80))
printf("%s \n" ,buf);
}
}

34
Output:
[student@gcet ~]$ vi pipes2.c
[student@gcet ~]$ cc pipes2.c
[student@gcet ~]$ ./a.out
Parent reading from pipe
Total 24
-rwxrwxr-x l student student 5563Aug 3 10:39 a.out
-rw-rw-r—l
Student student 340 jul 27 10:45 pipe2.c
-rw-rw-r—l student student
Pipes2.c
-rw-rw-r—l student student 401 34127 10:27 pipe2.c
student
Conclusion:
C program successfully executed using command pipe.

35
19.Communication between two unrelated processes using named pipe.
Aim: to implement C program that illustrate communication between two unrelated processes
using named pipe.
Source code:
#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:
[student@gcet ~]$ vi pipes1.c
[student@gcet ~]$ cc pipes1.c
[student@gcet ~]$ ./a.out
writing to file descriptor #4
reading from file descriptor #3
read"test"
Conclusion:
C program successfully executed using named pipe
36
20.Write 3 messages to it with different priority numbers.
Aim: to implement C program to create a message queue with read and write permissions to
write 3 messages to it with different priority numbers.
Source code:
#include <stdio.h>
#include <sys/ipc.h>
#include <fcntl.h>
#define MAX 255
struct mesg
{
long type;
char mtext[MAX];
} *mesg;
char buff[MAX];
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”);
}

37
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:
Student@ubuntu:~$ gcc msgq.c
Student@ubuntu:~$ cat > fact
Hello
Hai
Welcome
^z
Student@ubuntu:~$ ./msgq.out
Queue id :0
Mesgq created
Hello
Hai
welcome
Conslusion:
C program successfully executed using 3 messages to it with different priority numbers.

38
21.Receives the messages and displays them.
Aim: to implement C program that receives the messages and displays them.
Source code:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#define MSGSZ 128
typedef struct msgbuf
{
long mtype;
char mtext[MSGSZ];
} message_buf;
main()
{
int msqid;
key_t key;
message_buf rbuf;
key = 1234;
if ((msqid = msgget(key, 0666)) < 0)
{
perror("msgget");
exit(1);
}
if (msgrcv(msqid, &rbuf, MSGSZ, 1, 0) < 0) {
perror("msgrcv");
exit(1);
}
printf("%s\n", rbuf.mtext);
exit(0);
}

39
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
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?
Conclusion:
C program that successfully Receives the messages and displays them.

40
22.Cooperting processes to lock a resource for exclusive use:
Aim: to implement C program to allow cooperating processes to lock a resource for exclusive
use Semaphores and flock or lockf system calls.
Source code:
#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”);
41
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
Conclusion:
C program successfully allowed Cooperting processes to lock a resource for exclusive use:

42
23.Suspending and resuming processes using signals.
Aim: to implement C program that illustrate suspending and resuming processes using signals.
Source code:
#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;
}

43
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
Conclusion:
C program successfully Suspending and resuming processes using signals.

44
24.A producer consumer system with two processes.
Aim: To implement C program that implements a producer consumer system with two
processes(Using Semaphores).
Source code:
#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();
45
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);
}
break;
default:
for (i=0; i<NUM_LOOPS; i )
{
printf("producer: '%d'\n", i);
fflush(stdout);
sem_op.sem_num = 0;
sem_op.sem_op = 1;
sem_op.sem_flg = 0;
semop(sem_set_id, &sem_op, 1);
sleep(2);
if (rand() > 3*(RAND_MAX/4))
{
delay.tv_sec = 0;
delay.tv_nsec = 10;
nanosleep(&delay, NULL);
}
}
break;
46
}
return 0;
}

Output:
Student@ubuntu:~$ gcc sem.c
Student@ubuntu:~$ ./a.out
Semaphore set created
Consumer 0
Consumer 1
Producer 0 Producer 1
Conclusion:
C program successfully implements a producer consumer system with two processes(Using
Semaphores).

47
25.Interaction between server and client processes using Unix Domain Sockets.
Aim: To implement Client and server programs(using c) for interaction between server and
client processes usin Domain Sockets.
Source code:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
struct sockaddr_un address;
int socket_fd, nbytes;
char buffer[256];
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
{
printf("socket() failed\n");
return 1;
}
/* start with a clean address structure */
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(connect(socket_fd,
(struct sockaddr *) &address,
sizeof(struct sockaddr_un)) != 0)
{
printf("connect() failed\n");
return 1;
}
nbytes = snprintf(buffer, 256, "hello from a client");
write(socket_fd, buffer, nbytes);
48
nbytes = read(socket_fd, buffer, 256);
buffer[nbytes] = 0;
printf("MESSAGE FROM SERVER: %s\n", buffer);
close(socket_fd);
return 0;
}
server1.c:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int connection_handler(int connection_fd)
{
int nbytes;
char buffer[256];
nbytes = read(connection_fd, buffer, 256);
buffer[nbytes] = 0;
printf("MESSAGE FROM CLIENT: %s\n", buffer);
nbytes = snprintf(buffer, 256, "hello from the server");
write(connection_fd, buffer, nbytes);
close(connection_fd);
return 0;
}
int main(void)
{
struct sockaddr_un address;
int socket_fd, connection_fd;
socklen_t address_length;
pid_t child;
socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(socket_fd < 0)
49
{
printf("socket() failed\n");
return 1;
}
unlink("./demo_socket");
/* start with a clean address structure */
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "./demo_socket");
if(bind(socket_fd,
(struct sockaddr *) &address,
sizeof(struct sockaddr_un)) != 0)
{
printf("bind() failed\n");
return 1;
}
if(listen(socket_fd, 5) != 0)
{
printf("listen() failed\n");
return 1;
}
while((connection_fd = accept(socket_fd,
(struct sockaddr *) &address,
&address_length)) > -1)
{
child = fork();
if(child == 0)
{
/* now inside newly created connection handling process */
return connection_handler(connection_fd);
}
/* still inside server process */
close(connection_fd);
50
}
close(socket_fd);
unlink("./demo_socket");
return 0;
}

Output:
Student@ubuntu:~$gcc –o server1.out server1.c
Student@ubuntu:~$gcc client1.out client1.c
Student@ubuntu:~$ ./client1.out
MESSAGE FROM SERVER hello from the server
Student@ubuntu:~$ ./server1.out
MESSAGE FROM CLIENT hello from the CLIENT
Conclusion:
Successfully Client and server programs(using c) for interaction between server and client
processes usin Domain Sockets.

51
26.Interaction between server and client processes using Internet Domain sockets.
Aim: To implement client and server program(using c) for interaction between server and
client processes using Internet domain sockets
Source code:
Server program:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2)
{
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
52
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0) error("ERROR writing to socket");
return 0;
}
Client Program:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(char *msg)
{ perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3)
53
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server-
>h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
return 0;
54
}

Output:
Student@ubuntu:~$gcc –o server2.out server2.c
Student@ubuntu:~$gcc –o client2.out client2.c
Please enter the message
Hello world
Hello world I got ur message
Student@ubuntu:~$ ./server2.out
Here is the message hello world
Conclusion:
client and server program(using c) successfully executed for interaction between server and
client processes using Internet domain sockets

55
27.Two processes communicating using shared memory.
Aim: To implement C program that illustrate two processes communicating using shared
memory
Source code:
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
Struct country
{
Char name[30];
Char capital_city [30];
Char currency[30];
Int population;
};
Int main(int argc,char*argv[])
{
Int shm_id;
Char*shm_addr;
Int*countries_num;
Struct country*countries;
Struct shmid_ds shm_desc;
Shm_id=shmget(100,2048,IPC_CREAT|IPC_EXCL\0600);
If(shm_id==-1){
Perror(“main:shmget:”);
Exit(1);
}
Shm_addr=shmat(shm_id,NULL,0);
If(!shm_addr){
Perror(“main:shmat:”);
Exit(1);
}
Countries_num=(int*)shm_addr;
56
*countries_num=0;
Countries=(struct country*)((void*)shm_addr sizeof(int));
Strcpy(countries[0],name,”U.S.A”);
Strcpy(countries[0],capital_city,”WASHINGTON”);
Strcpy(countries[0],currency,”U.S.DOLLAR”);
Countries[0].population=250000000;
( countries_num) ;
Strcpy(countries[1].name,”israel”);
Strcpy(countries[1].capital_city,”jerushalem”);
Strcpy(countries[1].currency,”NEW ISRAEL SHEKED”);
Countries[1].population=6000000;
(*countries_num) ;
Strcpy(countries[2].name,”France”);
Strcpy(countries[2].capital_city,”paris”);
Strcpy(countries[2].currency,”Frank”);
Countries[2].population=60000000;
(*countries_num) ;
For(i=0;i<(*countries_num);i )
{
Printf(“country%d:\n”,i 1);
Printf(“name:%d:\n”,i 1);
Printf(“currency:%s:\n”,countries[i].currency);
Printf(“population:%d:\n”,countries[i].population);
}
If(shmdt(shm_addr)==-1){
Perror(“main:shmdt:”);
}
If(shmctl(shm_id,IPC_RMID,&SHM_DESC)==-1)
{
Perror(“main:shmctl:”);
}
return 0;
}
57
Output:
Student@ubuntu:~$gcc shm.c
Student@ubuntu:~$ ./a.out
Shared memory ID=65537 child pointer 3086680064
Child value =1
Shared memory ID=65537 child pointer 3086680064
Parent value=1
Parent value=42
Child value=42
Conclusion:
C program that successfully executed using two processes communicating using shared
memory

58
PROGRAM : 4

PROCESS CREATION, EXECUTION

// f3.c to display the environment variables

#include &lt;stdio.h&gt;

main(int argc, char **argv)

int i;

char **ptr;

extern char **environ;

printf(&quot;\n Invoked using execv function:&quot;);

printf(&quot;\n No. of arguments passed: %d&quot;, argc);

for(ptr=environ;*ptr!=0;ptr++)

printf(&quot;\n %s &quot;,*ptr);

printf(&quot;\n&quot;);

// f2.c to implement the different types of exec functions

#include &lt;stdio.h&gt;

#include &lt;stdlib.h&gt;

#include &lt;unistd.h&gt;

#include &lt;sys/types.h&gt;

#define HOME &quot;/home/murugan&quot;

#define HISTSIZE &quot;100&quot;

main()

59
pid_t pid;

char *argv[2];

char *env_init[3];

env_init[0]=HOME;

env_init[1]=HISTSIZE;

env_init[2]=&quot;NULL&quot;;

argv[0]=&quot;a&quot;;

argv[1]=&quot;b&quot;;

if ((pid = fork()) &lt; 0)

printf(&quot;\n\nfork error&quot;);

else if (pid == 0)

{ if ((execl(&quot;/media/sda11/murugan/lab/exec/f3&quot;, (char *)0)) &lt; 0 )

printf(&quot;\n execl error \n&quot;);

else

exit(0);

PROGRAM : 4

if ((pid = fork()) &lt; 0)

printf(&quot;\n\nfork error&quot;);

else if (pid == 0)

if ((execv(&quot;/media/sda11/murugan/lab/exec/f3&quot;, argv)) &lt; 0)

printf(&quot;\n execv error \n&quot;);

else

exit(0);
60
}

if ((pid = fork()) &lt; 0)

printf(&quot;\n\nfork error&quot;);

else if (pid == 0)

if ((execle(&quot;/media/sda11/murugan/lab/exec/f3&quot;, &quot;aa&quot;, &quot;bb&quot;, (char*)0,

env_init)) &lt; 0)

printf(&quot;\n execle error \n&quot;);

else

exit(0);

if ((pid = fork()) &lt; 0)

printf(&quot;\n\nfork error&quot;);

else if (pid == 0)

if ((execlp(&quot;./f3&quot;, &quot;aa&quot;, &quot;bb&quot;, (char*)0)) &lt; 0)

printf(&quot;\n execlp error \n&quot;);

else

exit(0);

if ((pid = fork()) &lt; 0)

printf(&quot;\n\nfork error&quot;);

else if (pid == 0)

61
if ((execvp(&quot;./f3&quot;, argv)) &lt; 0)

printf(&quot;\n execvp error \n&quot;);

else

exit(0);

if ((pid = fork()) &lt; 0)

printf(&quot;\n\nfork error&quot;);

else if (pid == 0)

if ((execve(&quot;./f3&quot;, argv, env_init )) &lt; 0)

printf(&quot;\n execve error \n&quot;);

else

exit(0);

OUTPUT : 4

PROCESS CREATION, EXECUTION

knoppix@Knoppix:/media/sda11/murugan/lab/exec$ cc f3.c -o f3

knoppix@Knoppix:/media/sda11/murugan/lab/exec$ f3

Invoked using execv function:

No. of arguments passed: 1

KDE_MULTIHEAD=false

HOSTNAME=Knoppix

SHELL=/bin/bash

TERM=xterm
62
XDM_MANAGED=/etc/sysconfig/xsession-

commands,maysd,mayfn,sched,method=classic

GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/knoppix/.gtkrc-

2.0:/ramdisk/home/knoppix/.kde/share/config/gtkrc-2.0

GTK_RC_FILES=/etc/gtk/gtkrc:/home/knoppix/.gtkrc:/ramdisk/home/knoppix/.kde/s

hare/config/gtkrc

WINDOWID=37748741

LC_ALL=C

USER=knoppix

KDEDIR=/usr

SESSION_MANAGER=local/Knoppix:/tmp/.ICE-unix/3645

KONSOLE_DCOP=DCOPRef(konsole-3741,konsole)

MAIL=/var/mail/knoppix

PATH=/home/knoppix/.dist/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/usr/local

/sbin:/usr/local/bin:/usr/games:/usr/NX/bin:.

KONSOLE_DCOP_SESSION=DCOPRef(konsole-3741,session- 1)

PWD=/media/sda11/murugan/lab/exec

LANG=C

SHLVL=2

HOME=/home/knoppix

LANGUAGE=us

XCURSOR_THEME=default

LOGNAME=knoppix

G_FILENAME_ENCODING=@locale

63
DISPLAY=:0.0

COLORTERM=

_=./f3

OLDPWD=/media/sda11/murugan/lab

knoppix@Knoppix:/media/sda11/murugan/lab/exec$ cc f2.c -o f2

knoppix@Knoppix:/media/sda11/murugan/lab/exec$ f2

Invoked using execv function:

No. of arguments passed: 0

KDE_MULTIHEAD=false

HOSTNAME=Knoppix

SHELL=/bin/bash

OUTPUT : 4

TERM=xterm

XDM_MANAGED=/etc/sysconfig/xsession-

commands,maysd,mayfn,sched,method=classic

GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/knoppix/.gtkrc-

2.0:/ramdisk/home/knoppix/.kde/share/config/gtkrc-2.0

GTK_RC_FILES=/etc/gtk/gtkrc:/home/knoppix/.gtkrc:/ramdisk/home/knoppix/.kde/s

hare/config/gtkrc

WINDOWID=37748741

LC_ALL=C

USER=knoppix

KDEDIR=/usr

SESSION_MANAGER=local/Knoppix:/tmp/.ICE-unix/3645

KONSOLE_DCOP=DCOPRef(konsole-3741,konsole)
64
MAIL=/var/mail/knoppix

PATH=/home/knoppix/.dist/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/usr/local

/sbin:/usr/local/bin:/usr/games:/usr/NX/bin:.

KONSOLE_DCOP_SESSION=DCOPRef(konsole-3741,session- 1)

PWD=/media/sda11/murugan/lab/exec

LANG=C

SHLVL=2

HOME=/home/knoppix

LANGUAGE=us

XCURSOR_THEME=default

LOGNAME=knoppix

G_FILENAME_ENCODING=@locale

DISPLAY=:0.0

COLORTERM=

_=./f2

OLDPWD=/media/sda11/murugan/lab

Invoked using execv function:

No. of arguments passed: 2

/home/murugan

100

NULL

Invoked using execv function:

65
No. of arguments passed: 2

KDE_MULTIHEAD=false

HOSTNAME=Knoppix

SHELL=/bin/bash

TERM=xterm

XDM_MANAGED=/etc/sysconfig/xsession-

commands,maysd,mayfn,sched,method=classic

OUTPUT : 4

GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/knoppix/.gtkrc-

2.0:/ramdisk/home/knoppix/.kde/share/config/gtkrc-2.0

GTK_RC_FILES=/etc/gtk/gtkrc:/home/knoppix/.gtkrc:/ramdisk/home/knoppix/.kde/s

hare/config/gtkrc

WINDOWID=37748741

LC_ALL=C

USER=knoppix

KDEDIR=/usr

SESSION_MANAGER=local/Knoppix:/tmp/.ICE-unix/3645

KONSOLE_DCOP=DCOPRef(konsole-3741,konsole)

MAIL=/var/mail/knoppix

PATH=/home/knoppix/.dist/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/usr/local

/sbin:/usr/local/bin:/usr/games:/usr/NX/bin:.

KONSOLE_DCOP_SESSION=DCOPRef(konsole-3741,session- 1)

PWD=/media/sda11/murugan/lab/exec

LANG=C

SHLVL=2
66
HOME=/home/knoppix

LANGUAGE=us

XCURSOR_THEME=default

LOGNAME=knoppix

G_FILENAME_ENCODING=@locale

DISPLAY=:0.0

COLORTERM=

_=./f2

OLDPWD=/media/sda11/murugan/lab

Invoked using execv function:

No. of arguments passed: 2

KDE_MULTIHEAD=false

HOSTNAME=Knoppix

SHELL=/bin/bash

TERM=xterm

XDM_MANAGED=/etc/sysconfig/xsession-

commands,maysd,mayfn,sched,method=classic

GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/knoppix/.gtkrc-

2.0:/ramdisk/home/knoppix/.kde/share/config/gtkrc-2.0

GTK_RC_FILES=/etc/gtk/gtkrc:/home/knoppix/.gtkrc:/ramdisk/home/knoppix/.kde/s

hare/config/gtkrc

WINDOWID=37748741

LC_ALL=C

USER=knoppix

67
KDEDIR=/usr

SESSION_MANAGER=local/Knoppix:/tmp/.ICE-unix/3645

KONSOLE_DCOP=DCOPRef(konsole-3741,konsole)

OUTPUT : 4

MAIL=/var/mail/knoppix

PATH=/home/knoppix/.dist/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/usr/local

/sbin:/usr/local/bin:/usr/games:/usr/NX/bin:.

KONSOLE_DCOP_SESSION=DCOPRef(konsole-3741,session- 1)

PWD=/media/sda11/murugan/lab/exec

LANG=C

SHLVL=2

HOME=/home/knoppix

LANGUAGE=us

XCURSOR_THEME=default

LOGNAME=knoppix

G_FILENAME_ENCODING=@locale

DISPLAY=:0.0

COLORTERM=

_=./f2

OLDPWD=/media/sda11/murugan/lab

Invoked using execv function:

No. of arguments passed: 2

/home/murugan

100

NULL
68
a

Invoked using execv function:

No. of arguments passed: 2

KDE_MULTIHEAD=false

HOSTNAME=Knoppix

SHELL=/bin/bash

TERM=xterm

XDM_MANAGED=/etc/sysconfig/xsession-

commands,maysd,mayfn,sched,method=classic

GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/knoppix/.gtkrc-

2.0:/ramdisk/home/knoppix/.kde/share/config/gtkrc-2.0

GTK_RC_FILES=/etc/gtk/gtkrc:/home/knoppix/.gtkrc:/ramdisk/home/knoppix/.kde/s

hare/config/gtkrc

WINDOWID=37748741

LC_ALL=C

USER=knoppix

KDEDIR=/usr

SESSION_MANAGER=local/Knoppix:/tmp/.ICE-unix/3645

KONSOLE_DCOP=DCOPRef(konsole-3741,konsole)

MAIL=/var/mail/knoppix

OUTPUT : 4

PATH=/home/knoppix/.dist/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/usr/local

69
/sbin:/usr/local/bin:/usr/games:/usr/NX/bin:.

KONSOLE_DCOP_SESSION=DCOPRef(konsole-3741,session- 1)

PWD=/media/sda11/murugan/lab/exec

LANG=C

SHLVL=2

HOME=/home/knoppix

LANGUAGE=us

XCURSOR_THEME=default

LOGNAME=knoppix

G_FILENAME_ENCODING=@locale

DISPLAY=:0.0

COLORTERM=

_=./f2

OLDPWD=/media/sda11/murugan/lab

knoppix@Knoppix:/media/sda11/murugan/lab/exec$

70
PROGRAM : 5 b

FIFO
// fifo.h

#include&lt;stdlib.h&gt;

#include&lt;stdio.h&gt;

#include&lt;string.h&gt;

#include&lt;fcntl.h&gt;

#include&lt;limits.h&gt;

#include&lt;sys/types.h&gt;

#include&lt;sys/stat.h&gt;

#include&lt;ctype.h&gt;

#define SERVERFIFO &quot;/tmp/sfifo&quot;

#define CLIENTFIFO &quot;/tmp/cfifo&quot;

#define BUFFSIZE 4992

struct datatopass

pid_t client_pid;

char data[BUFFSIZE+1];

};

71
PROGRAM : 8

MESSAGE QUEUES

// msg.h

#include&lt;sys/ipc.h&gt;

#include&lt;sys/msg.h&gt;

#include&lt;stdio.h&gt;

#include&lt;stdlib.h&gt;

#include&lt;sys/stat.h&gt;

#include&lt;sys/types.h&gt;

#include&lt;string.h&gt;

#include&lt;errno.h&gt;

#include&lt;limits.h&gt;

#include&lt;unistd.h&gt;

#define MSG_R 0400

#define MSG_W 0200

#define SVMSG_MODE (MSG_R|MSG_W)

#define MSGSZ 128

typedef struct msgbuf

long mtype;

char mtext[256];

}message_buf;

// msgcreat.c to create a message queue

#include&quot;msg.h&quot;

int main(int argc,char **argv)


72
{

int c,oflag,mqid;

oflag=SVMSG_MODE|IPC_CREAT;

mqid=msgget(1111,oflag);

exit(0);

// msgdel.c to delete a message queue

#include&quot;msg.h&quot;

int main(int argc,char **argv)

int mqid;

mqid=msgget(ftok(argv[1],0),0);

msgctl(mqid,IPC_RMID,NULL);

exit(0);

PROGRAM : 8

// msgpass.c to pass a message

#include&quot;msg.h&quot;

int main(int argc,char **argv)

int mqid;

size_t len;

long type;

message_buf sbuf;

73
if(argc!=5)

printf(&quot;error : usage message id&quot;);

exit(0);

len=atoi(argv[2]);

type=atoi(argv[3]);

mqid=msgget(1111,MSG_W);

sbuf.mtype=type;

srtcpy(sbuf.mtext,argv[4]);

msgsnd(mqid,&amp;sbuf,len,0);

exit(0);

// msgrec.c to receive a message

#include&quot;msg.h&quot;

#define MAXMSG (8192+sizeof(long))

int main(int argc,char **argv)

int c,flag,mquid;

long type;

ssize_t n;

message_buf buff;

type=0;

flag=0;

mquid=msgget(1111,MSG_R);
74
n=msgrcv(mquid,&amp;buff,MAXMSG,type,flag);

printf(&quot; read %d bytes, type = %ld, data = %s \n&quot;,buff.mtype,buff.mtext);

exit(0);

OUTPUT : 8

MESSAGE QUEUES

[user26@jetproxy murugan]$ cc msgcreat.c –o mc

[user26@jetproxy murugan]$ ipcs –q

-- -- -- Message Queues -- -- -- -

Key msqid owner perms used-bytes messages

0x00000457 65538 user26 600 0 0

[user26@jetproxy murugan]$ cc msgpass.c –o mp

[user26@jetproxy murugan]$ ./mp 1 1 100 a

[user26@jetproxy murugan]$ ipcs –q

-- -- -- Message Queues -- -- -- -

Key msqid owner perms used-bytes messages

0x00000457 65538 user26 600 1 1

[user26@jetproxy murugan]$ cc msgrec.c –o mr

[user26@jetproxy murugan]$ ./mr

Read 1 bytes, type=100, data=a

[user26@jetproxy murugan]$ cc msgdel.c –o md

[user26@jetproxy murugan]$ ipcs –q

-- -- -- Message Queues -- -- -- -

Key msqid owner perms used-bytes message

75
PROGRAM : 7

SEMAPHORES
// sem.h

#include&lt;sys/ipc.h&gt;

#include&lt;sys/sem.h&gt;

#include&lt;stdio.h&gt;

#include&lt;stdlib.h&gt;

#include&lt;unistd.h&gt;

#define SEM_R 0400

#define SEM_A 0200

#define SVSEM_MODE (SEM_R|SEM_A)

union semnum

int val;

struct semid_ds *buf;

unsigned short *array;

};

// createsem.c to create the semaphores

#include &quot;sem.h&quot;

int main(int argc,char **argv)

int c,oflag,semid,nsems;

oflag=SVSEM_MODE|IPC_CREAT;

while((c=getopt(argc,argv,&quot;e&quot;))!=-1)
76
{

switch(c)

case &#39;e&#39;:

oflag|=IPC_EXCL;

break;

if(optind!=argc-2)

printf(&quot;Usage : semcreat [-e] &lt;pn&gt; &lt;nsems&gt;&quot;);

exit(0);

nsems=atoi(argv[optind+1]);

semid=semget(ftok(argv[optind],0),nsems,oflag);

exit(0);

PROGRAM : 7

// semsetvalues.c set the values to the semaphores

#include &quot;sem.h&quot;

int main(int argc,char **argv)

int semid,nsems,i;

struct semid_ds seminfo;

77
unsigned short *ptr;

union semnum arg;

if(argc&lt;2)

printf(&quot;Usage: semset values &lt;pathname&gt; [values....]&quot;);

exit(-1);

semid=semget(ftok(argv[1],0),0,0);

arg.buf=&amp;seminfo;

semctl(semid,0,IPC_STAT,arg);

nsems=arg.buf-&gt;sem_nsems;

if(argc!=2)

printf(&quot;%d semaphores in set, %d values specified&quot;,nsems,argc-2);

exit(0);

ptr=calloc(nsems,sizeof(unsigned short));

arg.array=ptr;

for(i=0;i&lt;nsems;i++)

ptr[i]=atoi(argv[i+2]);

semctl(semid,0,SETALL,arg);

exit(0);

}
78
PROGRAM : 7

// semgetvalues.c to get the values from the semaphores

#include &quot;sem.h&quot;

int main(int argc,char **argv)

int semid,nsems,i;

struct semid_ds seminfo;

unsigned short *ptr;

union semnum arg;

if(argc!=2)

printf(&quot;Usage : semgetvalues &lt;pathname&gt;&quot;);

exit(-1);

semid=semget(ftok(argv[1],0),0,0);

arg.buf=&amp;seminfo;

semctl(semid,0,IPC_STAT,arg);

nsems=arg.buf-&gt;sem_nsems;

ptr=calloc(nsems,sizeof(unsigned short));

arg.array=ptr;

semctl(semid,0,GETALL,arg);

for(i=0;i&lt;nsems;i++)

printf(&quot;semval[ %d ] = %d &quot;,i,ptr[i]);

exit(0);

79
}

// removesem.c to remove the semaphores

#include&quot;sem.h&quot;

int main(int argc,char **argv)

int semid;

if(argc!=2)

printf(&quot;Usage : semrmid &lt;pathname&gt;&quot;);

exit(-1);

semid=semget(ftok(argv[1],0),0,0);

semctl(semid,0,IPC_RMID);

exit(0);

80
PROGRAM : 6

SHARED MEMORY
// “SHM .H”

#include&lt;stdio.h&gt;

#include&lt;sys/ipc.h&gt;

#include&lt;sys/shm.h&gt;

#include&lt;unistd.h&gt;

#define SHM_R 0444

#define SHM_W 0222

#define SVSHM_MODE (SHM_R|SHM_W)

#define PATHNAME 5678

#define LENGTH 10

// CREATE A SHARED MEMORY

#include &quot;shm.h&quot;

int main()

char *ptr;

int c,id,oflag;

oflag=SVSHM_MODE | IPC_CREAT;

id=shmget(PATHNAME,LENGTH,oflag);

ptr=shmat(id,NULL,0);

// SHARED MEMORY WRITE

#include &quot;shm.h&quot;

81
int main()

int i,id;

struct shmid_ds buff;

unsigned char *ptr;

id=shmget(PATHNAME,0,SVSHM_MODE);

ptr=shmat(id,NULL,0);

for(i=0;i&lt;10;i++)

*ptr++=i;

shmctl(id,IPC_STAT,&amp;buff);

printf(&quot;%ld&quot;,buff.shm_segsz);

exit(0);

PROGRAM : 6

// SHARED MEMORY READ

#include &quot;shm.h&quot;

int main()

int i,id;

struct shmid_ds buff;

unsigned char c,*ptr;

id=shmget(PATHNAME,0,SVSHM_MODE);

ptr=shmat(id,NULL,0);

shmctl(id,IPC_STAT,&amp;buff);
82
for(i=0;i&lt;buff.shm_segsz;i++)

c=*ptr++;

printf(&quot;ptr[%d]=%d&quot;,i,c);

exit(0);

// REMOVE SHARED MWEMORY

#include &quot;shm.h&quot;

int main()

int id;

id=shmget(PATHNAME,0,SVSHM_MODE);

shmctl(id,IPC_RMID,NULL);

exit(0);

OUTPUT : 6

SHARED MEMORY

// CREATE A SHARED MEMORY

[user26@jetproxy ~]$ cc crsh.c -o csh

[user26@jetproxy ~]$ ./csh

[user26@jetproxy ~]$ ipcs -m

-- -- -- Shared Memory Segments -- -- -- --

key shmid owner perms bytes nattch status

83
0x0000162e 1081351 user49 666 10 0

// WRITE A SHARED MEMORY

[user26@jetproxy ~]$ cc wrsh.c -o wsh

[user26@jetproxy ~]$ ./wsh

10

// READ A SHARED MEMORY

[user26@jetproxy ~]$ cc rdsh.c -o rsh

[user26@jetproxy ~]$ ./rsh

ptr[0]=0ptr[1]=0ptr[2]=0ptr[3]=0ptr[4]=0ptr[5]=0ptr[6]=0ptr[7]=0ptr[8]=0ptr[9]=0

// DELETE A SHARED MEMORY

[user26@jetproxy ~]$ cc delsh.c -o dsh

[user26@jetproxy ~]$ ./dsh

[user26@jetproxy ~]$ ipcs -m

-- -- -- Shared Memory Segments -- -- -- --

key shmid owner perms bytes nattch status

84
PROGRAM : 9

SOCKET PROGRAMING – TCP SOCKET


HEADER FILE

// tcp.h

#include&lt;string.h&gt;

#include&lt;sys/ipc.h&gt;

#include&lt;signal.h&gt;

#include&lt;sys/types.h&gt;

#include&lt;netinet/in.h&gt;

#include&lt;netdb.h&gt;

#include&lt;unistd.h&gt;

#include&lt;stdlib.h&gt;

#include&lt;stdio.h&gt;

#include &lt;errno.h&gt;

#define MAXLINE 4096

#define LISTENQ 1024

#define SERV_PORT 9897

#define SA struct sockaddr

SERVER PROGRAM

//tcpserv.c

#include &quot;tcp.h&quot;

void str_echo(int sockfd)

size_t n;

85
char buf[MAXLINE];

again:

while((n=read(sockfd,buf,MAXLINE)) &gt; 0)

write(sockfd,buf,n);

/*if((n&lt;0) &amp;&amp; (errno==EINTR))

goto again;

else*/

if(n&lt;0)

printf(&quot;str_echo read error&quot;);

int main(int argc,char **argv)

int listenfd,commfd;

pid_t childpid;

socklen_t clilen;

struct sockaddr_in servaddr;

struct sockaddr_in cliaddr;

listenfd=socket(AF_INET,SOCK_STREAM,0);

PROGRAM : 9 ` REG NO:2551126

memset(&amp;servaddr,0,sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_addr.s_addr=htonl(INADDR_ANY);

servaddr.sin_port=htons(SERV_PORT);

bind(listenfd,(SA *)&amp;servaddr,sizeof(servaddr));
86
listen(listenfd,LISTENQ);

for(;;)

clilen=sizeof(cliaddr);

commfd=accept(listenfd,(SA *)&amp;cliaddr,&amp;clilen);

if((childpid=fork())==0)

close(listenfd);

str_echo(commfd);

exit(0);

close(commfd);

CLIENT PROGRAM

//tcpclin.c

#include &quot;tcp.h&quot;

void str_cli ( FILE *fp , int sockfd)

char sendline[MAXLINE],recvline[MAXLINE];

while((fgets(sendline,MAXLINE,fp))!=NULL)

write(sockfd,sendline,strlen(sendline));

if((read(sockfd,recvline,MAXLINE))==0)
87
{

printf(&quot;str_cli:server terminated perminantly&quot;);

exit(-1);

fputs(recvline,stdout);

int main(int argc,char **argv)

int sockfd;

PROGRAM : 9 `

struct sockaddr_in servaddr;

if(argc!=2)

printf(&quot;usage:client&lt;ipaddress of server&gt;&quot;);

exit(-1);

sockfd=socket(AF_INET,SOCK_STREAM,0);

memset(&amp;servaddr,0,sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_port=htons(SERV_PORT);

inet_pton(AF_INET,argv[1],servaddr.sin_addr);

connect(sockfd,(SA *)&amp;servaddr,sizeof(servaddr));

str_cli(stdin,sockfd);

88
exit(0);

PROGRAM : 10

SOCKET PROGRAMMING - UDP SOCKET


// udp.h

#include&lt;sys/socket.h&gt;

#include&lt;netinet/in.h&gt;

#include&lt;netdb.h&gt;

#include&lt;stdio.h&gt;

#include&lt;unistd.h&gt;

#include&lt;fcntl.h&gt;

#include&lt;sys/ipc.h&gt;

#include&lt;signal.h&gt;

#include&lt;stdlib.h&gt;

#include&lt;sys/types.h&gt;

#include&lt;errno.h&gt;

#include&lt;string.h&gt;

#define MAXLINE 4096

#define LISTENQ 1024

#define SERVPORT 9897

#define SA struct sockaddr

//udpserv.c udpserver

#include&quot;udp.h&quot;

void udpecho(int sockfd,SA *pcliaddr,socklen_t clilen)


89
{

int n;

char msg[MAXLINE];

for(;;)

n=recvfrom(sockfd,msg,MAXLINE,0,pcliaddr,&amp;clilen);

sendto(sockfd,msg,n,0,pcliaddr,clilen);

int main(int argc,char **argv)

int sockfd;

struct sockaddr_in servaddr;

struct sockaddr_in cliaddr;

sockfd=socket(AF_INET,SOCK_DGRAM,0);

memset(&amp;servaddr,0,sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_addr.s_addr=htonl(INADDR_ANY);

PROGRAM : 10

servaddr.sin_port=htons(SERVPORT);

bind(sockfd,(SA *)&amp;servaddr,sizeof(servaddr));

udpecho(sockfd,(SA *)&amp;cliaddr,sizeof(cliaddr));

// udpcl.c udpclient

90
#include&quot;udp.h&quot;

void udpcli(FILE *fp,int sockfd,const SA *pservaddr,socklen_t servlen)

int n;

char sendline[MAXLINE],recvline[MAXLINE+1];

while(fgets(sendline,MAXLINE,stdin))

sendto(sockfd,sendline,strlen(sendline),0,pservaddr,servlen);

n=recvfrom(sockfd,recvline,MAXLINE,0,NULL,NULL);

recvline[n]=0;

fputs(recvline,stdout);

int main(int argc,char **argv)

int sockfd;

struct sockaddr_in servaddr;

memset(&amp;servaddr,0,sizeof(servaddr));

servaddr.sin_family=AF_INET;

servaddr.sin_port=htons(SERVPORT);

inet_pton(AF_INET,argv[1],&amp;servaddr.sin_addr);

sockfd=socket(AF_INET,SOCK_DGRAM,0);

udpcli(stdin,sockfd,(SA *)&amp;servaddr,sizeof(servaddr));

exit(0);
91
}

OUTPUT : 10

SOCKET PROGRAMMING - UDP SOCKET

[user26@jetproxy murugan]$ cc udpser.c –o us

[user26@jetproxy murugan]$ cc udpcl.c –o uc

[user26@jetproxy murugan]$ ./us&amp;

[3] 32349

[user26@jetproxy murugan]$ ./uc 192.168.005.102

SATHYABAMA UNIVERSITY

SATHYABAMA UNIVERSITY

DEPT OF MCA

DEPT OF MCA

92

You might also like