KEMBAR78
MCA Unix Lab Manual | PDF | Text File | Computer Science
0% found this document useful (0 votes)
68 views26 pages

MCA Unix Lab Manual

The document is a UNIX lab manual for MCA II semester students, detailing basic UNIX commands and their usage, including file management, process utilities, and directory handling. It also includes several shell script exercises for tasks such as file permission checking, word counting, and file merging. Additionally, it provides a C program example that demonstrates file copying using system calls.

Uploaded by

u19go21s0046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views26 pages

MCA Unix Lab Manual

The document is a UNIX lab manual for MCA II semester students, detailing basic UNIX commands and their usage, including file management, process utilities, and directory handling. It also includes several shell script exercises for tasks such as file permission checking, word counting, and file merging. Additionally, it provides a C program example that demonstrates file copying using system calls.

Uploaded by

u19go21s0046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

MCA – II SEMESTER - UNIX LAB MANUAL

PART A
1. Learn the use of basic UNIX commands-
a. To access information using date, history, man, who,
who am I, uptime, cal.
b. To display contents of files using cat, vi, more,
head, tail, grep, cmp, wc.
c. To manage files using cp, ls, mv, rm, chmod, find.
d. Proces utilities using ps, pid, ppid, tty, kill, exit.
e. Directory handling utilities using cd, mkdir, rmdir,
mv, pwd.
a. 1) date:- date command is used to display current date and
time to the nearest second.
$date
Output:Fri Nov 25 14:37:29 IST 2022.
2) history:- It is used to view previously executed
commands.
$history
Output:1 cal
2 cal 03
.
.
.
125 history
3) man:- Unix command manual, provides information about
the requested command.
$man ls
Output:Name
Ls – list directories/files
Syntax
Ls [options]…[File]…
.
.
.
4) who:- Displays the details of active users.
$who
Output: root console Dec 16 10:32
Vidya tty01 Dec 16 14:09
student tty02 Dec 16 14:15
5) who am i:- It displays the details of user who has
invoked the command.
$who am i
Output: student tty02 Dec 16 14:15
6) uptime:- This command gives one line display of the
following information. The current time, how long the system
has been running, how many users are currently logged on and
the system load averages for the past 1, 5 and 15 minutes.
$uptime
Output:14:45:30 up 16 min, 2 users, load average: 0.00, 0.04, 0.11.
7) cal:- It is used to invoke to see the calendar of any
specific month or a complete year.
$cal 01 2016
-→Displays 2016 January calendar.
b. 1) cat:- This command is used to create files, displays the
contents of files or used to concatenate the files.
$cat>abc.txt
Hi
Hello
<ctrl-d>
abc.txt file will be created.
$cat abc.txt
Hi
Hello
2) vi:- This is an editor that comes with unix operating
system.
$vi abc.sh
---→vi editor mode will be opened.
3) more:- This command is used to display the contents of
a file one page at a time.
$history|more
Output:- 1 cat
1 cal
.
.
.
<more>
51 ls
<more>
52 who
4) head:- This command is used to display the beginning
of the file.
$head -3 student.lst
Output:- 1234|amith raj|bca|comp science|12/10/1992|345
2345|guru raj|bsc|comp science|13/11/1992|456
6789|ram|bca|comp science|14/12/1992|987
5) tail:- It is used to display the end of the file.
$tail -3 student.lst
Output:- 3234|ram raj|bca|comp science|12/10/1992|845
6345|rahul|bsc|comp science|13/11/1992|886
7789|sundar|bca|comp science|14/12/1992|887
6) grep:- This command scans it’s input for a pattern
and displays lines containing the pattern, line number and
filename.
$grep “raj” student
Output: 1234|amith raj|bca|comp science|12/10/1992|345
2345|guru raj|bsc|comp science|13/11/1992|456
3234|ram raj|bca|comp science|12/10/1992|845
7) cmp:- This command compared the two files given as
arguments byte by byte and reports the location of the first
mismatch.
$cmp abc.txt xyz.txt
Output: abc.txt xyx.txt differ: byre 20 line 12.
8) wc:- This counts the number of lines, words and
characters in a file.
$wc abc.txt
Output: 5 13 57 abc.txt
c. 1) cp:- This command copies files from one location in
the system to another.
$cp abc.txt abc1.txt
---→ Copies contents of abc.txt to abc1.txt in the current
directory.
2) ls:-This produces a list of all files and directories in
the current directory.
$ls
Output:-abc.txt
abc1.txt
a.sh
3) mv:-It renames a file or directory or moves files to a
different directory.
$mv file1 file2
----→Changes the name of file file1 to file2.file1 will be
renamed by file2.
3) rm:- It deletes one or more files.
$rm file1
--→ Removes the file1 from current directory.
4) chmod:- It changes permissions of files or directories.
$chmod o+wx text1
$ls -l text1
Output:- -rw-rw-rwx 5 student student 1024 Dec 23 13:45 text1

$chmod 774 text2


$ls -l text2
Output:- -rwxrwxr-- 5 student student 1024 Dec 23 13:45 text2

d. 1) ps:-This command is used to display the attributes of a


process.
$ps
Output:- PID TTY TIME CMD
291 tty03 00:00:01 bash2
684 tty03 00:00:04 ps
2) pid:- Process Identification Number of the process
which is running.
$echo $$
Output:-3342
3) ppid:-It returns parent process identification number.
$ps -f
Output:- UID PID PPID C STIME TTY TIME CMD
Vidya 476 1 0 17:51:58 tty03 00:00:01 bash
4) tty:- It displays terminal details.
$tty
Output:- /dev/tty231
5) kill:- It is used to terminate a process.
$kill 105
---→ It terminates the job with PID 105.
6) exit:- It closes the terminal.
$exit
e. 1) cd:- This command changes the current directory to the
argument specified in the pathname.
$cd mca2
----→ Current directory will be changed to mca2.
2) mkdir:- This command is used to create a directory under
the current directory.
$mkdir mca2sem
----→ Creates a directory mca2sem in current directory.
3) rmdir:- It is used to remove directory, provided
directory should be empty.
$rmdir mca2sem
----→ Removes directory mca2sem from current directory.
4) pwd:- It displays the present/current working
directory.
$pwd
Output:- /home/student/mca2

2. Write a shell script that displays list of all the files in


the current directory to which the user has read, write and
execute permissions.

echo "Enter the directory name"


read dir
if [ -d $dir ]
then
cd $dir
ls>f
exec<f
while read line
do
if [ -f $line ]
then
if [ -r $line -a -w $line -a -x $line ]
then
echo "$line has all permissions"
else
echo "files not having all permissions"
fi
fi
done
fi

Output:$sh p2.sh
Enter the directory name
dir1
pgm1 has all permissions
fruit1 has all permissions
abc.sh not having all permissions.

3. Write a shell script that accepts a list of file names as


arguments, count and reports the occurrence of each word
that is present in the first argument file on other
argument files.
if [ $# -eq 0 ]
then
echo “no arguments”
else
tr “ “ “\n”<$1>temp
shift
for i in $*
do
tr “””\n”<$i>temp1
y=`wc –l < temp`
j=1
while [ $j le $y ]
do
x=`head –n $j temp | tail –l`
c=`grep –c “$x” temp1`
echo “$x occurred $c times”
echo $x $c
j=`expr $j + 1`

done
done
fi

Output:$sh p3.sh abc.txt xyz.txt


Hi occurred 2 times
Hello occurred 3 times

4. Write a shell script that accepts one or more file name


and converts all of them to uppercase, provided they
exist in the current directory.

echo "Enter filename"


read fn
if [ ! -f $fn ]
then
echo "Filename $fn doesnot exists"
exit 1
fi
tr '[a-z]' '[A-Z]'<$fn

Output:$sh p4.sh
Enter filename
fruit1
APPLE
BANANA
MANGO

5. Write grep commands to the following:


a. To select the lines from a file that has exactly 2
characters.
b. To select the lines from a file that has more than one
blank spaces.

a. To select the lines from a file that has exactly 2 characters.


echo "Enter file name: "
read file1
echo “Lines that has exactly has 2 characters”
grep -w '^..$' file1

Output: $sh 5a.sh


Enter file name:
f1
Lines that has exactly has 2 characters
Hi
Ab

b. To select the lines from a file that has more than one blank spaces.
echo "Enter file name "
read file1
grep " " $file1.txt >> ${dname}_error.txt

Output: $sh 5b.sh


Enter file name
f1
$cat _error.txt
Hi hhh
Ab bd

6. Write a shell script which accepts two file names as


arguments. Compare the contents. If they are same, then
delete the second file.

echo "Enter first file name "


read file1
echo "Enter second file name "
read file2

cmp -s $file1 $file2


total=`echo $?`
echo $total
if [ $total -eq 0 ]
then
echo "Contents of both files are same "
rm -v $file2

elif [ $total -eq 1 ]


echo "Contents of both files are not same"
else
echo "Error occurred during comparison"
fi

Output:$sh 6.sh
Enter first file name
f1
Enter second file name
f2
0
Contents of both files are same
removed f2

7. Write a shell script


a. to count number of lines in a file that do not contain
vowels.
b. to count number of characters, words, lines in a given
file.

a. to count number of lines in a file that do not contain vowels.

echo "Enter file name "


read file1
echo “Number of lines that do not contain vowels”
grep -c '^[^aeiou]*$' $file1

Output: $sh 7a.sh


Enter file name
f1
Number of lines that do not contain vowels
3

b. to count number of characters, words, lines in a given file.

echo “Enter file name”


read file1
c=`cat $file1 | wc -m`
w=`cat $file1 | wc -w`
l=`cat $file1 | wc -l`
echo “Number of characters in $file is $c”
echo “Number of words in $file is $w”
echo “Number of lines in $file is $l”
Output:-$sh 7b.sh
Enter file name
f1
Number of characters in f1 is 33
Number of words in f1 is 6
Number of lines in f1 is 4

8. Write a shell script to list all the files in a given


directory.

echo "Enter directory name"


read dir
if [ -d $dir ]
then
echo "List of files in the directory"
ls -l $dir|grep '^-'
else
echo "Enter proper directory name"
fi

Output:$sh p8.sh
Enter directory name
dir1
List of files in the directory
Total 110
-rw-rwxrw- 2 student student 212 Mar 12 19:32 fruit1
-rwxrwxrw- 1 student student 170 Apr 13 10:32 sample
-rw-rwxrw- 2 student student 210 Mar 12 11:32 prm.sh

9. Write a shell script to display list of users currently


logged in.

echo "List of users currently logged in is:"

set `who`
echo $1

Output:$sh p9.sh
List of users currently logged in is:
student
10. Write a shell script to read three text files in the
current directory and merge them into a single file and
returns a file descriptor for the new file.

echo "Enter first file name "


read file1
echo "Enter second file name "
read file2
echo "Enter third file name "
read file3

out="output.txt"
count=0

if [ ! -f $file1 ]
then
echo "$file1 not a file!"
exit 2
fi
if [ ! -f $file2 ]
then
echo "$file2 not a file!"
exit 3
fi
if [ ! -f $file3 ]
then
echo "$file3 not a file!"
exit 4
fi
cat $file1 $file2 $file3 >$out
count=$(cat $out | wc -w)
echo "$count words written to $out"

Output:$sh 10.sh
Enter first file name
f1
Enter second file name
f2
Enter third file name
f3
10 words written to output.txt
$cat output.txt
Hi hello
How are you
Hope you are fine
Bye
PART B
1. Write a program to copy a file into another using system calls.

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
char buf,n;
int sf,df;
if(argc!=3)
{
write(STDOUT_FILENO, "pgm1<source file><destination
file>\n",50);
exit;
}
else
{
sf=open(argv[1],O_RDONLY);
if(sf==-1)
{
perror("Source file error");
exit(0);
}
else
{
df=open(argv[2],O_WRONLY|O_CREAT,0641);
if(df==-1)
{
perror("Destination file error");
exit(0);
}
else
{
while((n==read(sf,&buf,1))!=-1)
{
write(df,&buf,1);
}
write(STDOUT_FILENO,"Files copied\n",15);
close(sf);
close(df);
}
}
}
return 0;
}
Output: $cc c1.c
$./a.out fruit1 newfile
$gedit newfile

2. Write a program using system call: create, open, write, close, stat, fstat, lseek.
#include<sys/types.h>
#include<sys/stat.h>
#include <fcntl.h>
int main()
{
int n,fd;
char buff[50];
printf("Enter text to write in the file:\n");
n= read(0, buff, 50);
fd=open("file",O_CREAT | O_RDWR, 0777);
write(fd, buff, n);
write(1, buff, n);
lseek(f,5,SEEK_CUR);
read(f,buff,10);
write(1,buff,10);
int close(int fd);
return 0;
}
Output: $cc c2.c
$./a.out fruit1 newfile
$gedit newfile

3. Write a program to create a child process and allow the


parent to display “parent” and the child to display “child” on
the screen.

#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>

int main()
{
int pid;
int status;
printf("Hello world\n");
pid=fork();
if(pid==-1)
{
perror("bad fork");
exit(1);
}
if(pid==0)
printf("I am the child process\n");
else
{
wait(&status);
printf("I am the parent process\n");
}
}

Output: $cc c3.c


$./a.out
Hello world
I am the child process
I am the parent process

4. Write a program to create a Zombie process.

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<errno.h>

int main()
{
int pid_t, child_pid;
int child_status;
child_pid=fork();
if(child_pid>0)
{
fprintf(stderr,"Parent process : %d\n",getpid());
sleep(30);
exit(0);
}
else if(child_pid==0)
{
fprintf(stderr,"child process:%d\n",getpid());
exit(0);
}
else if(child_pid==-1)
{
perror("fork() call failed");
exit(-1);
}
else
{
fprintf(stderr, "unknown return value of %d from fork()
call",child_pid);
exit(-2);
}
return(0);
}

Output:$cc c4.c
$./a.out
Parent process:4201
Child process:4202

5. Write a program to implement inter process communication using pipes.

#include<stdio.h>
#include<unistd.h>
int main()
{
int pipefds[2];
int returnstatus;
int pid;
char writemessages[2][20]={"Hi","Hello"};
char readmessages[20];
returnstatus=pipe(pipefds);
if(returnstatus==-1)
{
printf("Unable to create pipe\n");
return 1;
}
pid=fork();
if(pid==0)
{
read(pipefds[0],readmessages,sizeof(readmessages));
printf("Child Process-Reading from pipe-Message 1 is
%s\n",readmessages);
read(pipefds[0],readmessages,sizeof(readmessages));
printf("Child Process-Reading from pipe-Message 2 is
%s\n",readmessages);
}
else
{
printf("Parent Process-Writing to pipe-Message 1 is
%s\n",writemessages[0]);

write(pipefds[1],writemessages[0],sizeof(writemessages[0]));
printf("Parent Process-Writing to pipe-Message 2 is
%s\n",writemessages[1]);

write(pipefds[1],writemessages[1],sizeof(writemessages[1]));
}
}

Output:$cc c5.c
$./a.out
Parent Process-Writing to pipe-Message 1 is Hi
Parent Process-Writing to pipe-Message 2 is Hello
Child Process-Reading from pipe-Message 1 is Hi
Child Process-Reading from pipe-Message 2 is Hello

6. Simulate the following CPU scheduling algorithms


a. Round Robin
b. SJF

Round Robin:-

#include<stdio.h>
#include<stdlib.h>
void main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0, att=0,temp=0;

printf("Enter the number of processes:");


scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d :",i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice:");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
{
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
{
for(i=0;i<n;i++)
{
if(bu[i]!=0)
{
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
}

}
}
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}

printf("\n\tPROCESS\t BURST TIME\t WAITING TIME\t


TURNAROUNF TIME\n");
for(i=0;i<n;i++)
printf("\t%d\t %d\t\t
%d\t\t%d\n",i+1,ct[i],wa[i],tat[i]);
printf("\nAverage TurnAround Time is:%f",att/n);
printf("\nAverage Waiting Time is:%f",awt/n);
}

Output:$cc c6RR.c
$./a.out
Enter the number of processes:4
Enter Burst Time for process 1: 6
Enter Burst Time for process 2: 8
Enter Burst Time for process 3: 7
Enter Burst Time for process 4: 3
Enter the size of timeslice:3

PROCESS BURST TIME WAITING TIME TURNAROUND


TIME
1 6 9 15
2 8 15 23
3 7 17 24
4 3 9 12

Average TurnAround Time is: 18.500000


Average Waiting Time is: 12.50000

SJF:-

#include<stdio.h>

void main()
{
int p[20],bt[20],wt[20],tat[20],i,k,n,temp;
float wtavg,tatavg;

printf("\nEnter the number of processes:");


scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("\nEnter Burst Time for Process %d:",i);
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0]=wtavg=0;
tat[0]=tatavg=bt[0];
for(i=1;i<n;i++)
{
wt[i]=wt[i-1]+bt[i-1];
tat[i]=tat[i-1]+bt[i];
wtavg=wtavg+wt[i];
tatavg=tatavg+tat[i];
}
printf("\n\tPROCESS\t BURST TIME\tWAITING TIME\tTURNAROUND
TIME\n");
for(i=0;i<n;i++)
{
printf("\n\t%d\t\t %d\t\t %d\t\t
%d",p[i],bt[i],wt[i],tat[i]);
}
printf("\nAverage Waiting time %f:",wtavg/n);
printf("\nAverage TurnAround Time %f",tatavg/n);

Output:$cc c6SJF.c
$./a.out
Enter the number of processes: 4
Enter Burst Time for Process 0: 6
Enter Burst Time for Process 1: 8
Enter Burst Time for Process 2: 7
Enter Burst Time for Process 3: 3

PROCESS BURST TIME WAITING TIME TURNAROUND


TIME
3 3 0 3
0 6 3 9
2 7 9 16
1 8 16 24

Average waiting time 7.000000


Average TurnAround Time 13.00000

7. Write a program that illustrates file locking using semaphores.

#include <stdio.h>
#include <sys/file.h>
#include <error.h>
#include <sys/sem.h>
#define MAXBUF 100
#define KEY 1216
#define SEQFILE "seq_file"
int semid,fd;
void my_lock(int);
void my_unlock(int);
union semnum
{
int val;
struct semid_ds *buf;
short *array;
}arg;
int main()
{
int child, i,n, pid, seqno;
char buff[MAXBUF+1];
pid=getpid();
if((semid=semget(KEY, 1, IPC_CREAT | 0666))= = -1)
{
perror("semget");
exit(1);
}
arg.val=1;
if(semctl(semid,0,SETVAL,arg)<0)
perror("semctl");
if((fd=open(SEQFILE,2))<0)
{
perror("open");
exit(1);
}
pid=getpid();
for(i=0;i<2;i++)
{
my_lock(fd);
lseek(fd,01,0);
if((n=read(fd,buff,MAXBUF))<0)
{
perror("read");
exit(1);
}
printf("pid:%d, Seq no:%dn", pid, seqno);
seqno++;
sprintf(buff,"%dn", seqno);
n=strlen(buff);
lseek(fd,01,0);
if(write(fd,buff,n)!=n)
{
perror("write");
exit(1);
}
sleep(1);
my_unlock(fd);
}
}
void my_lock(int fd)
{
struct sembuff sbuf=(0, -1, 0);
if(semop(semid, &sbuf, 1)= =0)
printf("Locking: Resource…n");
else
printf("Error in Lockn");
}
void my_unlock(int fd)
{
struct sembuff sbuf=(0, 1, 0);
if(semop(semid, &sbuf, 1)= =0)
printf("UnLocking: Resource…n");
else
printf("Error in Unlockn");
}
Output:$cc c7.c
$./a.out
open
read
pid:6, Seq no:78
Locking: Resource…n
UnLocking: Resource…n

8. Write a program that implements producer-consumer system


with two process(using semaphore)

#include<stdio.h>
#include<stdlib.h>
int mutex=1;
int full=0;
int empty=10,x=0;
void producer()
{
--mutex;
++full;
--empty;
x++;
printf("\nProducer produces item %d",x);
++mutex;
}
void consumer()
{
--mutex;
--full;
++empty;
printf("\nconsumer consumes item %d",x);
x--;
++mutex;
}
int main()
{
int n,i;
printf("\n1.Press 1 for Producer");
printf("\n2. Press 2 for consumer");
printf("\n3. Press 3 for Exit");
for(i=1;i>0;i++)
{
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1) && (empty!=0))
{
producer();
}
else
{
printf("Buffer if full");
}

break;
case 2:
if((mutex==1) && (full!=0))
{
consumer();
}
else
{
printf("Bufer is empty");
}
break;
case 3:
exit(0);
break;
}
}
}

Output:$cc c8.c
$./a.out
1. Press 1 for Producer
2. Press 2 for consumer
3. Press 3 for Exit
Enter your choice:1

Producer produces item 1


Enter your choice:1

Producer produces item 2


Enter your choice:1

Producer produces item 3


Enter your choice:2
Consumer consumes item 1
Enter your choice:2

Consumer consumes item 2


Enter your choice:2

Consumer consumes item 3


Enter your choice:2
Buffer is empty
Enter your choice:3

9. Write a program that illustrates inter process communication using shared


memory system calls.

#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;
*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;
}
Output:-$cc c9.c
$./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

10.Write a program that illustrates the following:


a. Creating message queue.
b. Writing to a message queue
c. Reading from a message queue

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.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");
}
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:-$cc c10.c
$./a.out

Queue id:34

You might also like