0% found this document useful (0 votes)
39 views

OS LAB PROGRAMS RAJ

Uploaded by

chenuriraju17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

OS LAB PROGRAMS RAJ

Uploaded by

chenuriraju17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Department of CSE

JNTUH UCEJ

1. AIM:
Write C programs to simulate the following CPU scheduling algorithms
a) FCFS
b)SJF
c) Round Robin
d) Priority scheduling.

DESCRIPTION:
A)FIRST-COME FIRST-SERVE SCHEDULING (FCFS):

In this ,which process enter the ready queue first is served first. The OS maintains
DS that is ready queue. It is the simplest CPU scheduling algorithm. If a process
requests the CPU the nit is loaded into the ready queue, which process is the head of
the ready queue ,connect the CPU to that process.

ALGORITHM:
1- Input the processes along with their burst time (bt).
2- Find waiting time (wt) for all processes.
3- As first process that comes need not to wait so
waiting time for process 1 will be 0 i.e. wt[0] = 0.
4- Find waiting time for all other processes i.e. for
process i ->
wt[i] = bt[i-1] + wt[i-1] .
5- Find turnaround time = waiting_time + burst_time
for all processes.
6- Find average waiting time = total_waiting_time / no_of_processes.
7- Similarly, find average turnaround time =
total_turn_around_time / no_of_processes.

PROGRAM :
#include<stdio.h>
int main()
{
int bt[20],wt[20],tat[20],i,n;
float wtavg,tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
OPERATING SYSTEMS Page 1
Department of CSE
JNTUH UCEJ

for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
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("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND
TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
}
OUTPUT:

OPERATING SYSTEMS Page 2


Department of CSE
JNTUH UCEJ

b)SHORTEST JOB FIRST(SJF):

DESCRIPTION:
The criteria of this algorithm are which process having the smallest CPU
burst, CPU is assigned to that next process. If two process having the same CPU
burst time FCFS is used to break the tie.

ALGORITHM:
1- Traverse until all process gets completely
executed.
a) Find process with minimum remaining time at
every single time lap.
b) Reduce its time by 1.
c) Check if its remaining time becomes 0
d) Increment the counter of process completion.
e) Completion time of current process =
current_time +1;
e) Calculate waiting time for each completed
process.
wt[i]= Completion time - arrival_time-burst_time
f)Increment time lap by one.
2- Find turnaround time (waiting_time+burst_time).

PROGRAM :
#include<stdio.h>
int 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("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
OPERATING SYSTEMS Page 3
Department of CSE
JNTUH UCEJ

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\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND
TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%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);
}

OPERATING SYSTEMS Page 4


Department of CSE
JNTUH UCEJ

OUTPUT:

OPERATING SYSTEMS Page 5


Department of CSE
JNTUH UCEJ

c)ROUND ROBIN:

DESCRIPTION:
It is a primitive scheduling algorithm it is designed especially for time sharing
systems. In this,The CPU switches between the processes. When the time quantum
expired, the CPU switches to another job. As mal l unit of time called a quantum or
time slice. A time quantum is generally is a Circular queue new Processes are added
to the tail of the ready queue. If the process may have a CPU burst of less than one
time slice then the process release the CPU voluntarily. The scheduler will then
process to next process Ready queue otherwise; the pr ocess will be put at the tail of
the ready queue.

ALGORITHM:

1- Create an array rem_bt[] to keep track of remaining


burst time of processes. This array is initially a
copy of bt[] (burst times array)
2- Create another array wt[] to store waiting times
of processes. Initialize this array as 0.
3- Initialize time : t = 0
4- Keep traversing the all processes while all processes
are not done. Do following for i'th process if it is
not done yet.
a- If rem_bt[i] > quantum
(i) t = t + quantum
(ii) bt_rem[i] -= quantum;
c- Else // Last cycle for this process
(i) t = t + bt_rem[i];
(ii) wt[i] = t - bt[i]
(ii) bt_rem[i] = 0; // This process is over

OPERATING SYSTEMS Page 6


Department of CSE
JNTUH UCEJ

PROGRAM :

#include<stdio.h>
int 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 no 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++)
{
OPERATING SYSTEMS Page 7
Department of CSE
JNTUH UCEJ

wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND
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]);
}

OUTPUT:

OPERATING SYSTEMS Page 8


Department of CSE
JNTUH UCEJ

d) PRIORITY:
DESCRIPTION:
These are of two types. One is internal priority, second is external priority. The
CPU is allocated to the process with the highest priority. Equal priority processes
are scheduled in the FCFS order. Priorities are generally some fixed range of
Numbers such as 0to 409. The low numbers represent high priority.

ALGORITHM:
1- First input the processes with their burst time
and priority.
2- Sort the processes, burst time and priority
according to the priority.
3- Now simply apply FCFS algorithm.

PROGRAM :
#include<stdio.h>
int main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
printf("Enter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i);
scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
OPERATING SYSTEMS Page 9
Department of CSE
JNTUH UCEJ

bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = 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("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING
TIME\tTURNAROUND TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);
}
OUTPUT:

OPERATING SYSTEMS Page 10


Department of CSE
JNTUH UCEJ

2.AIM :
write programsusing the I/O system calls of UNIX/LINUX operating system

(open,read,write,close,fcntl,seek,stat,opendir( ), readdir( ). )

opendir( ), readdir( ) closedir()

ALGORITHM :
Step 1 : Start.
Step 2 : In the main function pass the arguments.
Step 3 : Create structure as stat buff and the variables as integer.
Step 4 : Using the for loop,initialization

SYSTEM CALLS USED:


1.opendir( ) Open a directory.
2.readdir( ) Read a directory.
3.closedir() Close a directory.

PROGRAM CODE 1:
#include<stdio.h>
#include<sys/types.h>
#include<sys/dir.h>
void main(int age,char *argv[])
{
DIR *dir; struct dirent *rddir;
printf("\n Listing the directory content\n");
dir=opendir(argv[1]);
while((rddir=readdir(dir))!=NULL)
{
printf("%s\t\n",rddir->d_name);
}
closedir(dir);
}

OPERATING SYSTEMS Page 11


Department of CSE
JNTUH UCEJ

OUTPUT:
RP
Roshi.c
first.c
pk6.c
f2 abc FILE1

RESULT:
Thus the program was executed and verified successfully

AIM :
write programs using the I/O system calls of UNIX/LINUX operating system

( open, read, write, close, fcntl, seek, stat, opendir( ), readdir( ). )

DESCRIPTION:
In computing , a system call is the programmatic way in which a computer
program requests a service from The kernel of the operating system it is executed
on.This may include hardware-related services, creation of the operating Systems
new processes, and communication with integral kernel services such as process
scheduling.Types of operating systems: process control, file management, device
management ,information management, Communication.
(It is a method used by process to request on action by the operating system.)

ALGORITHM:

Read from stdin=>read from fd0:


When ever we write any character from keyboard, it read from stdin through fd0
and save to filenamed/dev/tty.
Write to stdout=>writetofd1:
When ever we see any out put to the video screen, it’s from the file named/dev/t ty
and written to stdout in screen through fd1.
Write to stderr=>writetofd2:
We see any error to the video screen ,it is also from that file write to stderr in
screen through fd2.

OPERATING SYSTEMS Page 12


Department of CSE
JNTUH UCEJ

PROGRAM CODE 2:
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/types.h>
#include<stdlib.h>
#include<dirent.h>
int main(){
int fd;
fd=open("foo.txt",O_RDONLY | O_CREAT);
printf("fd=%d\n",fd);
if(fd==-1){
printf("file is empty");
}
char x[15],y[15];
printf("enter the message");
gets(x);
if(lseek(fd,x,SEEK_SET) < 0)
return 1;
write(fd,x,sizeof(x));
read(fd,y,sizeof(y));
//puts(y);
//close(fd);
struct stat sfile;
stat("foo.txt",&sfile);
printf("st_mode=%o",sfile.st_mode);
close(fd);
int exists;
DIR *d;
struct dirent *de;
d = opendir(".");
if (d == NULL) {
fprintf(stderr, "Couldn't open \".\"\n");
exit(1);
}
for (de = readdir(d); de != NULL; de = readdir(d)) {
exists = stat(de->d_name, &sfile);
OPERATING SYSTEMS Page 13
Department of CSE
JNTUH UCEJ

if (exists < 0) {
fprintf(stderr, "%s not found\n", de->d_name);
} else {
printf("%s %lld\n", de->d_name, sfile.st_size);
}
}
closedir(d);
//return 0;
}

OUTPUT:
fd=3
enter the message kaju
st_mode=100666. 0
.. 0
a.exe 54883
aksh.c 965
aksh.exe 60954
aksh.txt 971
dir.c 606
dir.exe 59401
fnctl.c 831
foo.txt 13
opclscall.c 390
opclscall.exe 54719
open.txt 15
opencall.c 554
opencall.exe 54547
read.c 321

OPERATING SYSTEMS Page 14


Department of CSE
JNTUH UCEJ

3.AIM:
Write a C program to stimulate Bankers algorithms for Deadlock Avoidance and
Prevention.
ALGORITHM:
Safety Algorithm
The algorithm for finding out whether or not a system is in a safe state can be
described as follows:

1. Let Work and Finish be vectors of length ‘m’ and ‘n’ respectively. Initialize:
Work= Available Finish [i]=false; for i=1,2,……,n

2. Find an i such that both a) Finish [i]=false b) Need_i<=work if no such i exists


goto step (4)

3. Work=Work + Allocation_i Finish[i]= true goto step(2)

4. If Finish[i]=true for all i, then the system is in safe state

Resource-RequestAlgorithm
1.If Requesti <=Needi
Go to step(2) otherwise ,raise an error condition ,since the process
has exceed edits maximum claim.
2.If Requesti <=Available
Gotostep(3);otherwise,Pi must wait,since there sources are not available.
3.Have the system pretend to have allocated the requested resources
to process Pi by modifying the state as follows:
Available=Available–Requesti
Allocationi =Allocationi +Requesti
Needi =Needi–Request

OPERATING SYSTEMS Page 15


Department of CSE
JNTUH UCEJ

DEADLOCK AVOIDANCE:
PROGRAM:

#include<stdio.h>
int main()
{
int n,m,i,j,k,avail[10];
int alloc[10][10],max[10][10];
printf(“enter Number of processes”);
scanf(“%d”,&n);
printf(“enter Number of resources”);
scanf(“%d”,&m);
printf(“enter allocated resources”);
for (i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf(“%d”,&alloc[i][j]);
}
}
printf(“enter max matrix”);
for (i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf(“%d”,&max[i][j]);
}
}
printf(“enter available resources”);
for(i=0;i<n;i++)
{
scanf(“%d”,&avail);
}
int f[n],ans[n],ind=0;
for(k=0;k<n;k++){
f[k]=0;
}

OPERATING SYSTEMS Page 16


Department of CSE
JNTUH UCEJ

int need[n][m];
for(i=0;i<n;i++){
for(j=0;j<m;j++)
need[i][j]=max[i][j]-alloc[i][j];
}
int y=0;
for(k=0;k<5;k++){
for(i=0;i<n;i++){
if(f[i]==0){
int flag=0;
for(j=0;j<m;j++){
if(need[i][j]>avail[j]){
flag=1;
break;
}
}
if(flag==0){
ans[ind++]=i;
for(y=0;y<m;y++)
avail[y]+=alloc[i][y];
f[i]=1;
}
}
}
}
printf("Following is the SAFE Sequence\n");
for(i=0;i<n-1;i++)
printf("P%d->",ans[i]);
printf("P%d",ans[n-1]);
return(0);
}

OUTPUT:
Enter number of processes:5
Enter number of resources:3
Enter allocated resources:
010

OPERATING SYSTEMS Page 17


Department of CSE
JNTUH UCEJ

200
302
211
002
Enter max matrix:
753
322
902
422
533
Enter available resources:
3
3
2
Following is the SAFE sequence:
p1 - > p3->p4->p0->p2

OPERATING SYSTEMS Page 18


Department of CSE
JNTUH UCEJ

DEADLOCK PREVENTION:

#include<stdio.h>
#include<conio.h>
void main()
{
int found,flag,l,p[4][5],tp,tr,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
clrscr();
printf("Enter total no of processes");
scanf("%d",&tp);
printf("Enter total no of resources");
scanf("%d",&tr);
printf("Enter claim (Max. Need) matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&c[i][j]);
}
printf("Enter allocation matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&p[i][j]);
}
printf("Enter resource vector (Total resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&r[i]);
}
printf("Enter availability vector (available resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}

OPERATING SYSTEMS Page 19


Department of CSE
JNTUH UCEJ

for(i=1;i<=tp;i++)
{
sum=0;
for(j=1;j<=tr;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=tp;i++)
{ for(l=1;l<k;l++)
if(i!=m[l])
{
flag=1;
for(j=1;j<=tr;j++)
if(c[i][j]<temp[j])
{
flag=0;
break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=tr;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{
found=0;
OPERATING SYSTEMS Page 20
Department of CSE
JNTUH UCEJ

for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
getch();
}

OUTPUT:
Enter total no. of processes : 4
Enter total no. of resources : 5
Enter claim (Max. Need) matrix :
01001
00101
00001
10101
Enter allocation matrix :
10110
11000
00010
00000
Enter resource vector (Total resources) :
21121
Enter availability vector (available resources) :
00001
deadlock causing processes are : 2 3

OPERATING SYSTEMS Page 21


Department of CSE
JNTUH UCEJ

4.AIM:
Write a C program to implement the Producer–Consumer problem using
Semaphores using UNIX/LINUX system call.

DESCRIPTION:
Producer consumer problem is also known as bounded buffer problem. In this
problem we have two processes, producer and consumer, who share a fixed size
buffer.Producer work is to produce data or items and put in buffer. Consumer work
is to remove data from buffer and consume it. We have to make sure that producer
Do not produced a t a when buffer Is full and consumer do not remove data when
buffer is empty.

ALGORITHM:

Producer process:
do{
PRODUCEITEM
wait(empty);
wait(mutex);
PUT ITEM IN BUFFER
signal(mutex);
signal(full);
}while(1);
Consumerprocess:
do{
wait(full);
wait(mutex);
REMOVEITEMFROMBUFFER
signal(mutex);
signal(empty);
CONSUMEITEM
}while(1);

OPERATING SYSTEMS Page 22


Department of CSE
JNTUH UCEJ

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main(){
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
printf("\n Enter your choice:");
scanf("%d",&n);
switch(n)
{
case1:if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case2:if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case3:
exit(0);
break;
}
}
return0;
}
int wait(int s)
{
return(--s);
OPERATING SYSTEMS Page 23
Department of CSE
JNTUH UCEJ

}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}
voidconsumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}

OUTPUT:
1.producer
2.consumer
3.exit
Producer produces the item 1
Enter your choice:1
Producer produces the item 2
Enter your choice:1
Producer produces the item 3
Enter your choice:2
Consumer consumes item 3
Enter your choice:2
Consumer consumes item 2
OPERATING SYSTEMS Page 24
Department of CSE
JNTUH UCEJ

Enter your choice:2


Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:3

OPERATING SYSTEMS Page 25


Department of CSE
JNTUH UCEJ

5.SHARED MEMORY AND IPC

AIM
To write a C program to implement shared memory and inter process
communication.

a) Pipes b) FIFO C)Message queues d)Shared Memory

a)Pipes

#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);
}
}

OPERATING SYSTEMS Page 26


Department of CSE
JNTUH UCEJ

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

b)FIFO

#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:
writing to file descriptor #4
reading from file descriptor #3
read"test"

OPERATING SYSTEMS Page 27


Department of CSE
JNTUH UCEJ

C. Message Queues
File: msgq_send.c
/* Filename: msgq_send.c */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define PERMS 0644


struct my_msgbuf {
long mtype;
char mtext[200];
};

int main(void) {
struct my_msgbuf buf;
int msqid;
int len;
key_t key;
system("touch msgq.txt");

if ((key = ftok("msgq.txt", 'B')) == -1) {


perror("ftok");
exit(1);
}

if ((msqid = msgget(key, PERMS | IPC_CREAT)) == -1) {


perror("msgget");
exit(1);
}
printf("message queue: ready to send messages.\n");
printf("Enter lines of text, ^D to quit:\n");
buf.mtype = 1; /* we don't really care in this case */
OPERATING SYSTEMS Page 28
Department of CSE
JNTUH UCEJ

while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {


len = strlen(buf.mtext);
/* remove newline at end, if it exists */
if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");
}
strcpy(buf.mtext, "end");
len = strlen(buf.mtext);
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");

if (msgctl(msqid, IPC_RMID, NULL) == -1) {


perror("msgctl");
exit(1);
}

printf("message queue: done sending messages.\n");


return 0;
}
OUTPUT
message queue: ready to send messages.
Enter lines of text, ^D to quit:
this is line 1
this is line 2
message queue: done sending messages.

File: msgq_recv.c
/* Filename: msgq_recv.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
OPERATING SYSTEMS Page 29
Department of CSE
JNTUH UCEJ

#define PERMS 0644


struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void) {
struct my_msgbuf buf;
int msqid;
int toend;
key_t key;

if ((key = ftok("msgq.txt", 'B')) == -1) {


perror("ftok");
exit(1);
}
if ((msqid = msgget(key, PERMS)) == -1) { /* connect to the queue */
perror("msgget");
exit(1);
}
printf("message queue: ready to receive messages.\n");

for(;;) { /* normally receiving never ends but just to make conclusion


/* this program ends wuth string of end */
if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("recvd: \"%s\"\n", buf.mtext);
toend = strcmp(buf.mtext,"end");
if (toend == 0)
break;
}

printf("message queue: done receiving messages.\n");


system("rm msgq.txt");
return 0;
}
OPERATING SYSTEMS Page 30
Department of CSE
JNTUH UCEJ

OUTPUT
message queue: ready to receive messages.
recvd: "this is line 1"
recvd: "this is line 2"
recvd: "end"
message queue: done receiving messages.

OPERATING SYSTEMS Page 31


Department of CSE
JNTUH UCEJ

d) SHARED MEMORY FOR WRITER PROCESS


#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;

int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);

// shmget returns an identifier in shmid


int shmid = shmget(key,1024,0666|IPC_CREAT);

// shmat to attach to shared memory


char *str = (char*) shmat(shmid,(void*)0,0);

printf("Write Data : ");


gets(str);

printf("Data written in memory: %s\n",str);

//detach from shared memory


shmdt(str);

return 0;
}

OUTPUT:
Write Data: HI KMIIT
Data written in memory: HI KMIT

OPERATING SYSTEMS Page 32


Department of CSE
JNTUH UCEJ

SHARED MEMORY FOR READER PROCESS


#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;

int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);

// shmget returns an identifier in shmid


int shmid = shmget(key,1024,0666|IPC_CREAT);

// shmat to attach to shared memory


char *str = (char*) shmat(shmid,(void*)0,0);

printf("Data read from memory: %s\n",str);

//detach from shared memory


shmdt(str);

// destroy the shared memory


shmctl(shmid,IPC_RMID,NULL);

return 0;
}
OUTPUT:
Data read from memory: HI KMIT

OPERATING SYSTEMS Page 33


Department of CSE
JNTUH UCEJ

ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5:Fill is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution

PROGRAM:
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/sem.h>
int main()
{
int id,semid,count=0,i=1,j;
int *ptr; id=shmget(8078,sizeof(int),IPC_CREAT|0666);
ptr=(int *)shmat(id,NULL,0);
union semun
{
int val;
struct semid_ds *buf; ushort *array;
}u;

struct sembuf sem;


semid=semget(1011,1,IPC_CREAT|0666);
ushort a[1]={1};
u.array=a;
semctl(semid,0,SETALL,u);
while(1)
{
sem.sem_num=0;
sem.sem_op=-1;
sem.sem_flg=0;
semop(semid,&sem,1);
*ptr=*ptr+1;
printf("process id:%d countis :%d \n",getpid(),*ptr);
OPERATING SYSTEMS Page 34
Department of CSE
JNTUH UCEJ

for(j=1;j<=1000000;j++)
{
sem.sem_num=0;
sem.sem_op=+1;
sem.sem_flg=0;
semop(semid,&sem,1);
}
}
shmdt(ptr);
}

RESULT:
Thus the program was executed

OPERATING SYSTEMS Page 35


Department of CSE
JNTUH UCEJ

6.AIM:
Write C programs to simulate the following memory management techniques.
a) paging b)segmentation

a)PAGING:

DESCRIPTION:
paging is a memory management scheme by which a computer stores and
retrieves data from secondary storage[a] for use in main memory.[1] In this scheme,
the operating system retrieves data from secondary storage in same-size blocks
called pages. Paging is an important part of virtual memory implementations in
modern operating systems, using secondary storage to let programs exceed the size
of available physical memory

PROGRAM CODE 1:
#include<stdio.h>
main()
{
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset;
int s[10], fno[10][20];
printf("\nEnter the memory size -- ");
scanf("%d",&ms);
printf("\nEnter the page size -- ");
scanf("%d",&ps);
nop = ms/ps;
printf("\nThe no. of pages available in memory are -- %d ",nop);
printf("\nEnter number of processes -- ");
scanf("%d",&np);
rempages = nop;
for(i=1;i<=np;i++)
{
printf("\nEnter no. of pages required for p[%d]-- ",i);
scanf("%d",&s[i]);
if(s[i] >rempages)
{
printf("\nMemory is Full");
break;
OPERATING SYSTEMS Page 36
Department of CSE
JNTUH UCEJ

}
rempages = rempages - s[i];
printf("\nEnter pagetable for p[%d] --- ",i);
for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}
printf("\nEnter Logical Address to find Physical Address ");
printf("\nEnter process no. and pagenumber and offset -- ");
scanf("%d %d %d",&x,&y, &offset);
if(x>np || y>=s[i] || offset>=ps)
printf("\nInvalid Process or Page Number or offset");
else
{
pa=fno[x][y]*ps+offset;
printf("\nThe Physical Address is -- %d",pa);
}
}

PROGRAM CODE 2:
#include<stdio.h>
#define MAX 50
int main()
{
int page[MAX],i,n,f,ps,off,pno;
int choice=0;
printf("\nEnter the no of pages in memory: ");
scanf("%d",&n);
printf("\nEnter page size: ");
scanf("%d",&ps);
printf("\nEnter no of frames: ");
scanf("%d",&f);
for(i=0;i<n;i++)
page[i]=-1;
printf("\nEnter the page table\n");
printf("(Enter frame no as -1 if that page is not present in any frame)\n\n");
printf("\npageno\tframeno\n-------\t-------");
for(i=0;i<n;i++)
OPERATING SYSTEMS Page 37
Department of CSE
JNTUH UCEJ

{
printf("\n\n%d\t\t",i);
scanf("%d",&page[i]);
}
do
{
printf("\n\nEnter the logical address(i.e,page no & offset):");
scanf("%d%d",&pno,&off);
if(page[pno]==-1)
printf("\n\nThe required page is not available in any of frames");
else
printf("\n\nPhysical address(i.e,frame no & offset):%d,%d",page[pno],off);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
return 1;
}
OUTPUT:

OPERATING SYSTEMS Page 38


Department of CSE
JNTUH UCEJ

b)SEGMENTATION:

DESCRIPTION:

In Operating Systems, Segmentation is a memory management technique in


which, the memory is divided into the variable size parts. Each part is known as
segment which can be allocated to a process. The details about each segment are
stored in a table called as segment table.

PROGRAM:

#include<stdio.h>
int main()
{
int nm,n,i,x=0,y=1,p,of,t=300;
printf("Enter the memory size\n");
scanf("%d",&nm);
printf("Enter the number of segments\n");
scanf("%d",&n);
int s[n];
for(i=0;i<n;i++)
{
printf("Enter the size of segment %d : ",i+1);
scanf("%d",&s[i]);
x+=s[i];
if(x>nm)
{
printf("Memory full segment %d is not allocated\n",i+1);
x-=s[i];
s[i]=0;
}
}
printf("------OPERATIONS ON SEGMENTS------\n");
while(y==1)
{
printf("Enter the segment number for operation : ");
scanf("%d",&p);

OPERATING SYSTEMS Page 39


Department of CSE
JNTUH UCEJ

printf("Enter the offset :");


scanf("%d",&of);
if(s[p-1]==0)
{
printf("Segment not allocated memory\n");
}
else if(of>s[p-1])
{
printf("Out of Range\n");
}
else
{
printf("Segment %d physical address is from %d to %d\nAddress for operation is
%d\n",p,t,t+s[p-1],t+of);
}
printf("Enter 1 to continue\n");
scanf("%d",&y);
}
}

OUTPUT:

OPERATING SYSTEMS Page 40

You might also like