Operating-System-Lab-Manual R22
Operating-System-Lab-Manual R22
WEEK-1
Write C programs to simulate the following CPU Scheduling algorithms.
a. FCFS
b. SJF
c. Round Robin
d. Priority
Aim: Write a C program to implement the various process scheduling mechanisms such as FCFS scheduling.
Algorithm:
KCEA Page 1
OPERATING SYSTEMS
Program:
#include<stdio.h>int
main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enternumberofprocess:");
scanf("%d",&n);
printf("\nEnterBurstTime:\n");
for(i=0;i<n;i++)
{
printf("p% d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //containsprocess number
}
wt[0]=0; //waiting time for first processwillbezero
//calculatewaitingtime for(i=1;i<n;i++)
{
wt[i]=0; for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
avg_wt=(float)total/n; //averagewaitingtime
total=0;
printf("\n Process \t BurstTime \t Waiting Time \t Turn around Time");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turn around time
total+=tat[i];
printf("\np%d\t\t%d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
KCEA Page 2
OPERATING SYSTEMS
Output:
KCEA Page 3
OPERATING SYSTEMS
b) SJF(ShortestJob First)
Aim: Write a C program to implement the various process scheduling mechanisms such as SJF Scheduling.
Algorithm:
7: Calculate
Averagewaitingtime = TotalwaitingTime/ Numberofprocess
AverageTurnaroundtime=TotalTurnaroundTime/Numberofprocess
8: Stop the process
KCEA Page 4
OPERATING SYSTEMS
Program:
#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enternumberofprocess:");
scanf("%d",&n);
printf("\nEnterBurstTime:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //containsprocess number
}
//sortingbursttimeinascendingorderusingselectionsort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0; //waitingtimeforfirstprocesswillbezero
//calculatewaitingtime
for(i=1;i<n;i++)
{
wt[i]=0;
KCEA Page 5
OPERATING SYSTEMS
for(j=0;j<i;j++) wt[i]
+=bt[j];
total+=wt[i];
}
printf("\nProcess\tBurst Time\tWaitingTime\tTurnaroundTime");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculateturnaroundtime
total+=tat[i];
printf("\np%d\t\t%d\t\t%d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
Output:
KCEA Page 6
OPERATING SYSTEMS
c) Round Robin
Aim:Write a C program to implement the various process scheduling mechanisms such as Round Robin
Scheduling.
Algorithm
1:Start the process
2:Accept the number of processes in the ready Queue and time quantum (or) time slice
3:ForeachprocessinthereadyQ,assigntheprocessidandaccepttheCPUbursttime
KCEA Page 7
OPERATING SYSTEMS
Program:
#include<stdio.h >
main()
{
int st[10],bt[10],wt[10],tat[10],n,tq;
int i,count=0,swt=0,stat=0,temp,sq=0;
float awt,atat;
printf("enter the number of processes");
scanf("%d",&n);
printf("enter the burst time of each process/n");
for(i=0;i<n;i++)
{
printf("p%d",i+1);
scanf("%d",&bt[i]);
st[i]=bt[i];
}
printf("enterthetimequantum");
scanf("%d",&tq);
while(1)
{
for(i=0,count=0;i<n;i++)
{
temp=tq;
if(st[i]==0)
{
count++;
continue;
}
if(st[i]>tq)
st[i]=st[i]-tq;
KCEA Page 8
OPERATING SYSTEMS
else
if(st[i]>=0)
{
temp=st[i];
st[i]=0;
}
sq=sq+temp;
tat[i]=sq;
}
if(n==count) break;
}
for(i=0;i<n;i++)
{
wt[i]=tat[i]-bt[i];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("process no\t burst time \t waiting time\t turn around time\n"); for(i=0;i<n;i++)
printf("%d\t\t %d\t\t %d\t\t %d\n",i+1,bt[i],wt[i],tat[i]);
printf("avg wt time=%f,avg turn around time=%f",awt,atat);
}
KCEA Page 9
OPERATING SYSTEMS
Output:
KCEA Page 10
OPERATING SYSTEMS
d) Priority
Aim: Write a C program to implement the various process scheduling mechanisms suchas Priority
Scheduling.
Algorithm:
1:Start the process
2:Accept the number of processes in the ready Queue
3: For each process in the ready Q, assign the process id and accept the CPU burst time4: Sort the ready
queue according to the priority number.
5:Set the waiting of the first process as‘0’and its burst time as its turn around time
6: For each process in the Ready Q calculate
Waiting time for process(n)=waiting time of process (n-1)+Burst time of process(n-1)
Turn around time for Process(n)=waiting time of Process(n)+Burst time for process(n)
7: Calculate
Average waiting time = Total waiting Time/ Number of process
AverageTurnaroundtime=TotalTurnaroundTime/NumberofprocessStep8:Stopthe process
KCEA Page 11
OPERATING SYSTEMS
Program:
#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],pri[20],i,j,k,n,total=0,pos,temp; float
avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}
KCEA Page 12
OPERATING SYSTEMS
total+=wt[i];
}
avg_wt=(float)total/n; //average waiting time
total=0;
printf("\nProcess\tBurstTime\tPriority\tWaitingTime\tTurnaroundTime"); for(i=0;i<n;i+
+)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\np%d\t\t%d\t\t%d\t\t%d\t\t\t%d",p[i],bt[i],pri[i],wt[i],tat[i]);
}
KCEA Page 13
OPERATING SYSTEMS
Output:
KCEA Page 14
OPERATING SYSTEMS
WEEK-2
Write programs using the I/O system calls of UNIX/LINUX operating system (open, read, write,
close, fcntl, seek, stat, opendir, readdir)
Theory:
There are 5 basic system calls that Unix provides for file I/O.
1. Create: Used to Create a new empty file
Syntax : int creat(char *filename, mode_t mode) file
name: name of the file which you want to create mode :
indicates permissions of new file.
2. open:Used to Open the file for reading,writing or both.
Syntax:int open(char*path,int flags [ ,int mode] );
Path:path to file which you want to use flags :
How you like to use
O_RDONLY: read only, O_WRONLY : write only, O_RDWR : read and write,O_CREAT:create file if it
doesn’t exist, O_EXCL: prevent creation if it already exists
3. close: Tells the operating system you are done with a file descriptor and Close the file which
pointed by fd.
Syntax:int close(int fd); fd
:file descriptor
4. read: From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input
into the memory area indicated by buf.A successful read() updates the access time for the file.
Syntax:int read(int fd,char*buf,int size);
fd: file descripter
buf:buffer to read data from
cnt: length of buffer
5. write: Writes cnt bytes from buf to the file or socket associated with fd. cnt should not be greater
than INT_MAX(defined in the limits.h header file).If cnt is zero,write()simply returns0 without
attempting any other action.
Syntax: int write(int fd,char*buf,int size);
fd: file descripter
buf:buffer to write data to
cnt: length of buffer
*File descriptor is integer that uniquely identifies an open file of the process.
KCEA Page 15
OPERATING SYSTEMS
Algorithm
1. Start the program.
2. Open a file for O_RDWR for R/W,O_CREATE for creating a file, O_TRUNC for truncate a file.
3. Using get char (),read the character and stored in the string[] array.
4. The string [] array is write into a file close it.
5. Then the first is opened for read only mode and read the characters and displayed it and close the
file.
6. Stop the program.
Program
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
int main()
{
int n,i=0;
int f1,f2;
char c,strin[100]; f1=open("data",O_RDWR|O_CREAT|
O_TRUNC); while((c=get char())!='\n')
{
strin[i++]=c;
}
strin[i]='\0';
write(f1,strin,i);
close(f1);
f2=open("data",O_RDONLY);
read(f2,strin,0); printf("\n%s\
n",strin); close(f2);
return0;
Output:
Hai
Hai
KCEA Page 16
OPERATING SYSTEMS
Algorithm:
1. Start the program
2. Open a file in read mode
3. Read the content so the file
4. Use lseek to change the position of pointer in the read process
5. Stop
KCEA Page 17
OPERATING SYSTEMS
Program:
#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include<sys/types.h>
int main()
{
int file=0;
if((file=open("testfile.txt",O_RDONLY))<1)
return1;
char buffer[19];
if(read(file,buffer,19)!=19)
return1;
printf("%s\n",buffer);
if(lseek(file,10,SEEK_SET)<0)
return1;
if(read(file,buffer,19)!=19)
return1;
printf("%s\n",buffer);
return0;
}
Output:
KCEA Page 18
OPERATING SYSTEMS
Theory:
The following are the various operations using directories
1. Creating directories.
Syntax: int mkdir(const char*pathname ,mode_tmode);
2. The ‘pathname’ argument is used for the name of the directory.
3. Opening directories
Syntax: DIR*opendir(const char*name);
4. Reading directories.
Syntax:struct dirent*readdir(DIR *dirp);
5. Removing directories.
Syntax: int rmdir(constchar*pathname);
6. Closing the directory.
Syntax: int closedir(DIR *dirp);
7. Getting the current working directory.
Syntax: char*getcwd(char*buf,size_tsize);
Algorithm:
1. Start the program
2. Print a menu to choose the different directory operations
3. To create and remove a directory ask the user for name and create and remove the same
respectively.
4. To open a directory check whether directory exists or not. If yes open the directory . If it does
not exists print an error message.
5. Finally close the opened directory.
6. Stop
KCEA Page 19
OPERATING SYSTEMS
Program:
#include<stdio.h>
#include<fcntl.h>
#include<dirent.h>
main()
{
chard[10];int c,op;DIR*e;
struct dirent *sd;
printf("**menu**\n1.createdir\n2.removedir\n3.readdir\nenterurchoice");
scanf("%d",&op);
switch(op)
{
case 1:
printf("enter dirname\n");
scanf("%s",&d);
c=mkdir(d,777);
if(c==1)
printf("dirisnotcreated");
else
printf("diris created");
break;
case 2:
printf("enterdirname\n");
scanf("%s",&d);
c=rmdir(d);
if(c==1)
printf("dirisnotremoved");
else
printf("dirisremoved");
break;
case 3:
printf("enterdirnametoopen");
scanf("%s",&d);
e=opendir(d);
if(e==NULL)
printf("dir does not exist");
else
{
printf("direxist\n");
while((sd=readdir(e))!=NULL)
printf("%s\t",sd->d_name);
}
closedir(e);
break;
}
}
KCEA Page 20
OPERATING SYSTEMS
Output:
KCEA Page 21
OPERATING SYSTEMS
WEEK-3
Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention
a) Aim
Write a C program to simulate the Bankers Algorithm for Deadlock Avoidance.
Data structures
1. n-Number of process, m-number of resource types.
2. Available: Available[j]=k, k –instance of resource type Rj is available.
3. Max: If max[i,j]=k, Pimay request atmost k instances resource Rj.
4. Allocation: If Allocation [i,j]=k, Pi allocated to k instances of resource Rj
5. Need: If Need[I,j]=k, Pi may need k more instances of resource type Rj,
6. Need[I,j]=Max[I,j]-Allocation[I,j];
Safety Algorithm
1. Work and Finish be the vector of length m and n respectively ,Work=Available and
Finish[i]=False.
2. Find an i such that both
3. Finish[i] =False
4. Need<=Work
5. If no such I exist go to step 4.
6. work=work + Allocation ,Finish[i]=True;
7. If Finish[1] =True for all I, then the system is in safe state.
If the resulting resource allocation state is safe, the transaction is completed and process Pi is allocated its
resources. However, if the state is unsafe, the Pi must wait for Request i and the old resource-allocation
state is restore.
KCEA Page 22
OPERATING SYSTEMS
Algorithm:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether it is possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. Or not if we allow the request.
10. Stop the program.
Program:
#include<stdio.h>
int main ()
{
int allocated[15][15],max[15][15],need[15][15],avail[15],tres[15], work[15],
flag[15];
int pno,rno,i,j,prc,count,t,total; count= 0;
//clrscr();
KCEA Page 23
OPERATING SYSTEMS
}
printf("\n available resources:\n");
for (j = 1; j <= rno; j++)
{
avail[j] =0;
total= 0;
for(i =1; i <=pno; i++)
{
total+= allocated[i][j];
}
avail[j]=tres[j]-total;
work[j] = avail[j];
printf ("%d\t", work[j]);
}
do
{
KCEA Page 24
OPERATING SYSTEMS
printf("%4d", allocated[i][j]);
}
printf ("|");
for(j =1; j <=rno;j++)
{
printf("%4d", max[i][j]);
}
printf ("|");
for(j =1; j <=rno;j++)
{
printf("%4d", need[i][j]);
}
}
prc=0;
KCEA Page 25
OPERATING SYSTEMS
max[prc][j]=0;
flag[prc]=1;
printf("%d",work[j]);
}
}
}
while(count !=pno&&prc!=0);
if(count==pno)
printf("\n The system is in a safe state!!");
else
printf("\n The system is in an unsafe state!!");
return 0;
}
KCEA Page 26
OPERATING SYSTEMS
Output:
KCEA Page 27
OPERATING SYSTEMS
KCEA Page 28
OPERATING SYSTEMS
b) Aim
Write a C program to simulate Bankers Algorithm for Deadlock Prevention
Algorithm:
1. Start
2. Attacking Mutex condition: never grant exclusive access. But this may not be possible for several
resources.
3. Attacking preemption : not something you want to do.
4. Attacking hold and wait condition : make a process hold at the most 1 resource at a time.Make all
the requests at the beginning. All or nothing policy. If you feel, retry. eg. 2- phase locking 34
5. Attacking circular wait: Order all the resources. Make sure that the requests are issued in the
correct order so that there are no cycles present in the resource graph. Resources numbered 1 ... n.
Resources can be requested only in increasing order. ie. you cannot request a resource whose no
is less than any you may be holding.
6. Stop
Program:
#include<stdio.h>
int max[10][10],alloc[10][10],need[10][10],avail[10],i,j,p,r,finish[10]={0},flag=0;
main( )
{
printf("\n SIMULATION OF DEADLOCK PREVENTION\n ");
printf("Enter no. of processes, resources\n");
scanf("%d %d", &p, &r);
printf("Enter allocation matrix");
for(i=0;i<p; i++)
for(j=0;j<r; j++)
scanf("%d", &alloc[i][j]);
printf("\n enter max matrix");
for(i=0;i<p; i++) /*reading the maximum matrix and available matrix*/
for(j=0;j<r; j++)
scanf("%d", &max[i][j]);
printf("\n enter available matrix");
for(i=0;i<r; i++)
scanf("%d", &avail[i]);
KCEA Page 29
OPERATING SYSTEMS
for(i=0;i<p;i++)
for(j=0;j<r;j++) need[i][j]=max[i]
[j]-alloc[i][j]; fun(); /*calling
function*/ if(flag==0)
{
if(finish[i]!=1)
{
printf("\nFailing: Mutual exclusion");
for(j=0;j<r;j++)
{
/*checking for mutual exclusion*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}
fun();
printf("\n By allocating required resources to process %d deadlock is prevented ", i);
printf("\n lack of preemption");
for(j=0;j<r;j++)
{
if(avail[j]<need[i][j])
avail[j]=need[i][j];
alloc[i][j]=0;
}
fun();
printf("\n dead lock is prevented by allocating needed resources");
printf("\nfailing:Hold and Wait condition");
for(j=0;j<r;j++)
{
/*checking hold and wait condition*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}
fun();
printf("\n AVOIDING ANY ONE OF THE CONDITION, U CAN PREVENT DEADLOCK");
}
}
}
fun()
{
while(1)
{
for(flag=0,i=0;i<p; i++)
KCEA Page 30
OPERATING SYSTEMS
{
if(finish[i]==0)
{
for(j=0;j<r; j++)
{
if(need[i][j]<=avail[j])
continue;
else
break;
}
if(j==r)
{
for(j=0;j<r; j++) avail[j]
+=alloc[i][j]; flag=1;
finish[i]=1;
}
}
}
KCEA Page 31
OPERATING SYSTEMS
Output:
KCEA Page 32
OPERATING SYSTEMS
WEEK-4
Write a C program to implement the Producer–Consumer problem using semaphores using UNIX/LINUX
system calls.
Aim:
Write a C program to implement the Producer–Consumer problem using semaphores using UNIX/LINUX
system calls.
Algorithm:
1. The Semaphore mutex, full & empty are initialized.
2. In the case of producer process
3. Produce an item in to temporary variable.
If there is empty space in the buffer check the mutex value for enter into the critical section. If
the mutex value is 0, allow the producer to add value in the temporary variable to the buffer.
4. In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0, remove
item from buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.
5. Print the result
KCEA Page 33
OPERATING SYSTEMS
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("\nEnter your choice:");
scanf ("%d", &n);
switch (n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer ();
else
printf("Bufferisfull!!");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer ();
else
printf("Bufferisempty!!");
break;
case 3:
exit(0);
break;
}
}
return0;
KCEA Page 34
OPERATING SYSTEMS
}
int wait(int s)
{
return(--s);
}
int signal(ints)
{
return(++s);
}
void producer ()
{
mutex=wait(mutex);
full = signal (full);
empty=wait(empty);
x++;
printf("\nProducerproducestheitem%d",x);
mutex = signal (mutex);
}
void consumer()
{
mutex=wait(mutex);
full = wait (full);
empty=signal(empty);
printf("\nConsumerconsumesitem%d",x);
x--;
mutex=signal(mutex);
}
KCEA Page 35
OPERATING SYSTEMS
Output
KCEA Page 36
OPERATING SYSTEMS
WEEK :5
ALGORITHM:
KCEA Page 37
OPERATING SYSTEMS
Program:
a) PIPE PROCESSING
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#defineMSG_LEN64
int main()
{
int result;
int fd[2];
char message[MSG_LEN];
char recvd_msg[MSG_LE];
result=pipe(fd);
//Creating a pipe
//fd[0] is for reading and fd[1] is for writing
if(result<0)
{
perror("pipe ");
exit(1);
}
strncpy(message," Linux World!!",MSG_LEN);
result=write(fd[1],message, strlen(message));
if(result<0){
perror("write");
exit(2);
}
strncpy(message, "Understanding ",MSG_LEN);
result=write(fd[1],message, strlen(message));
if(result < 0){
perror("write");
exit(2);
}
strncpy(message,"Concepts of ",MSG_LEN);
result=write(fd[1],message,strlen(message));
if (result <0){
perror("write");
exit(2);
}
KCEA Page 38
OPERATING SYSTEMS
result=write(fd[1],message,strlen(message));
if (result < 0)
perror("write");
exit(2);
}
result=read(fd[0],recvd_msg,MSG_LEN);
if(result<0)
{
perror("read");
exit(3);
}
printf("%s\n",recvd_msg);return0;
}
#include <unistd.h>
#include<linux/stat.h>
#defineFIFO_FILE "MYFIFO"
int main(void)
{
FILE *fp;
char readbuf[80];
while(1)
{
fp=fopen(FIFO_FILE,"r");
fgets(readbuf, 80, fp);
printf("Received string:%s\n",readbuf);
fclose(fp);
}
return(0);
}
KCEA Page 39
OPERATING SYSTEMS
b) FIFO
Program:
#include <stdio.h>
#include <stdlib.h>
#include<sys/stat.h>
#include <stdio.h>
#include<stdlib.h>
int main(intargc,char*argv[])
{
FILE *fp;
if(argc !=2) {
printf("USAGE:fifoclient[string]\n");
exit(1);
}
if((fp=fopen(FIFO_FILE,"w"))==NULL){
perror("fopen");
exit(1);
}
fputs(argv[1], fp);
fclose(fp); return(0);
}
KCEA Page 40
OPERATING SYSTEMS
#include <stdio.h>
#include <sys/ipc.h>
#include<sys/msg.h>
//structure for message queue
struct mesg_buffer {
long msg_type;
charmsg_text[100];
} message;
int main()
{
key_tkey;
int msgid;
//ftok to generate unique key
key = ftok("progfile", 65);
//msg get creates a message queue
//and returns identifier
msgid=msgget(key,0666|IPC_CREAT);\
message.mesg_type = 1;
return0;
}
KCEA Page 41
OPERATING SYSTEMS
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_tkey;
int msgid;
return0;
}
KCEA Page 42
OPERATING SYSTEMS
#include <stdio.h>
#include<sys/ipc.h>
#include<sys/msg.h>
//structure for message queue
struct mesg_buffer
{
longmesg_type;
charmesg_text[100];
} message;
int main()
{ key_tkey
; int msgid;
//ftok to generate unique key
key = ftok("progfile", 65);
return0;
}
KCEA Page 43
OPERATING SYSTEMS
OUTPUT:Th
us the Piping
processusing
IPC program
was executed
and verified
successfully
KCEA Page 44
OPERATING SYSTEMS
WEEK :6
Aim: Write C programs to simulate the following memory management techniques.
a)Paging
ALGORITHM:
KCEA Page 45
OPERATING SYSTEMS
Program:
#include<stdio.h>
#include<conio.h>
main()
int ms,ps,nop,np,rempages,i,j,x,y,pa,offset;
int s[10],fno[10][20];
scanf("%d", &ms);
printf("\nEnterthepagesize--");
scanf("%d", &ps);
nop =ms/ps;
scanf("%d", &np);
rempages =nop;
for(i=1;i<=np;i++)
scanf("%d", &s[i]);
if(s[i]>rempages)
break;
KCEA Page 46
OPERATING SYSTEMS
for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
printf("\n Enter process no. and page number and offset -- ");
if(x>np||y>=s[i]||offset>=ps)
pa= fno[x][y]*ps+offset;
}
getch ();
KCEA Page 47
OPERATING SYSTEMS
OUTPUT:
KCEA Page 48
OPERATING SYSTEMS
b) Segmentation
Aim: To write a C program to implement memory management using segmentation
Algorithm:
Step1: Start the program.
Step2: Read the base address, number of segments, size of each segment, memory limit.
Step3: If memory address is less than the base address display “invalid memory limit”.
Step4: Create the segment table with the segment number and segment address and display it.
Step 5: Read the segment number and displacement.
Step6: If the segment number and displacement is valid compute the real address and display the same.
Step7: Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
struct list
{
int seg;
int base;
int limit;
struct list *next;
} *p;
Void insert(struct list*q, int base,int limit, int seg)
{
if(p==NULL)
{
p=malloc(sizeof(Structlist));
p->limit=limit;
p->base=base;
p->seg=seg;
p->next=NULL;
}
else
{
while(q->next!=NULL)
{
Q=q->next;
Printf(“yes”)
}
q->next=malloc(sizeof(Structlist));
q->next ->limit=limit;
q->next->base=base;
q->next ->seg=seg;
KCEA Page 49
OPERATING SYSTEMS
q->next->next=NULL;
}
}
int find(struct list*q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->limit;
}
int search(structlist*q, int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->base;
}
main()
{
p=NULL;
int seg, offset, limit, base, c, s,
physical;
printf(“Enter segment table/n”);
printf(“Enter-1 assegment value for termination\n”);
do
{
printf(“Enter segment number”);
scanf(“%d”,&seg);
if(seg!=-1)
{
printf(“Enter base value:”);
scanf(“%d”, &base);
insert(p,base, lmit,seg);
}
}
while(seg!=-1)
printf(“Enter offset:”);
KCEA Page 50
OPERATING SYSTEMS
scanf(“%d”, &offset);
printf(“Enter b segmentation number:”);
scanf(“%d”, &seg);
c=find(p, seg);
s=search(p, seg);
if(offset<c)
{
physical=s+offset;
printf(“Address in physical memory %d\n”, physical);
}
else
{
printf(“error”);
}
OUTPUT:
KCEA Page 51
OPERATING SYSTEMS
WEEK: 7
Write a c program to simulate Page replacement policies a) FCFS b) LRU c) Optimal
DESCRIPTION
Page replacement is basic to demand paging. It completes the separation between logical memory and physical
memory. With this mechanism, an enormous virtual memory can be provided for programmers on a smaller
physical memory. There are many different page-replacement algorithms. Every operating system probably has
its own replacement scheme. A FIFO replacement algorithm associates with each page the time when that page
was brought into memory. When a page must be replaced, the oldest page is chosen. If the recent past is used as
an approximation of the near future, then the page that has not been used for the longest period of time can be
replaced. This approach is the Least Recently Used (LRU) algorithm. LRU replacement associates with each
page the time of that page's last use. When a page must be replaced, LRU chooses the page that has not been used
for the longest period of time. Least frequently used (LFU) page-replacement algorithm requires that the page
with the smallest count be replaced. The reason for this selection is that an actively used page should have a large
reference count.
PROGRAM
a) FIFOPAGEREPLACEMENTALGORITHM
#include<stdio.h>
#include<conio.h>
main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
clrscr();
printf("\n Enter the length of reference string--");
scanf("%d", &n);
printf("\n Enter the reference string--");
for(i=0;i<n; i++)
scanf("%d",&rs[i]);
printf("\n Enter no. of frames--");
scanf("%d", &f);
for(i=0;i<f;i++)
m[i]=-1;
KCEA Page 52
OPERATING SYSTEMS
if(k==f)
printf("\t PF No. %d", pf);
printf("\n");
if(count==f)
count=0;
}
printf("\n The number of Page Faults using FIFO are %d", pf);
getch();
}
INPUT
Enterthelengthofreferencestring–20
Enter the reference string --701203 042303 21201701 Enter no. of
frames -- 3
OUTPUT
The Page Replacement Process is–
-1 -1 PFNo.1
0 -1 PFNo.2
0 1 PFNo.3
0 1 PFNo.4
0 1
3 1 PFNo.5
3 0 PFNo.6
3 0 PFNo.7
2 0 PFNo.8
2 3 PFNo.9
2 3 PFNo.10
2 3
2 3
1 3 PFNo.11
1 2 PFNo.12
1 2
1 2
1 2 PFNo.13
0 2 PFNo.14
0 1 PFNo.15
KCEA Page 53
OPERATING SYSTEMS
fframe[count]=-1;
printf("lru page replacement algorithm in c");
printf("Enter pages (press -999 to exit):\n");
for(count=0;count<high; count++)
{
scanf("%d", &tmp);
if(tmp==-999)
break;
page[count]=tmp; np+
+;
}
for(count=0;count<np;count++)
{
flag=0;
for(n1=0;n1<nf;n1++)
{
if(fframe[n1]==page[count])
{
printf("\n\t");
flag=1;
break;
}
}
/*program for lru page replacement algorithm in c*/
if(flag==0)
{
for(n1=0;n1<nf;n1++) used[n1]=0;
for(n1=0,tmp=count-1;n1<nf-1;n1++, tmp--)
{
for(k=0;k<nf; k++)
KCEA Page 54
OPERATING SYSTEMS
{
if(fframe[k]==page[tmp])
used[k]=1;
}
}
for(n1=0;n1<nf;n1++)
if(used[n1]==0)
index=n1;
fframe[index]=page[count];
printf("\nFault:");
pf++;
}
for(k=0;k<nf;k++) printf("%d\
t",fframe[k]);
} //lru algorithm in c
printf("\n number of total page faults is:%d", pf);
getch();
}
output
lru page replacement algorithm in c
Enter no. of frames
Enter pages(press -999toexit): 2 3 2 1
5245
325-999
-1-1 2Fault:
-1-1 2Fault:
-132Fault:
132Fault:
132
152Fault:
452Fault:
452
453Fault:
253Fault:
253
253
KCEA Page 55
OPERATING SYSTEMS
ALGORITHM DESCRIPTION
Optimal page replacement algorithm has the lowest page-fault rate of all algorithms and will never suffer
from Belady's anomaly. The basic idea is to replace the page that will not be used for the longest period of
time. Use of this page-replacement algorithm guarantees the lowest possible page fault rate for a fixed
number of frames. Unfortunately, the optimal page- replacement algorithm is difficult to implement,
because it requires future knowledge of the reference string.
PROGRAM
#include<stdio.h>
int n;
main()
{
int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s;
int count=1,pf=0,p=0;
float pfr;
clrscr();
printf("Enter maximum limit of the sequence: ");
scanf("%d",&max);
printf("\nEnter the sequence: ");
for(i=0;i<max;i++)
scanf("%d",&seq[i]);
printf("\nEnterno.offrames:");
scanf("%d",&n);
fr[0]=seq[0];
pf++;
printf("%d\t",fr[0]);
i=1;
while(count<n)
{
flag=1;
p++;
for(j=0;j<i;j++)
{
if(seq[i]==seq[j])
flag=0;
}
if(flag!=0)
{
fr[count]=seq[i];
printf("%d\t",fr[count]);
count++;
pf++;
KCEA Page 56
OPERATING SYSTEMS
}
i++;
}
printf("\n");
for(i=p;i<max;i++)
{
flag=1;
for(j=0;j<n;j++)
{
if(seq[i]==fr[j])
flag=0;
}
if(flag!=0)
{
for(j=0;j<n;j++)
{
m=fr[j]
;for(k=i;k<max;k++)
{
if(seq[k]==m)
{
pos[j]=k;
break;
}
else
pos[j]=1;
}
}
for(k=0;k<n;k++)
{
if(pos[k]==1)
flag=0;
}
if(flag!=0)
s=find max(pos);
if(flag==0)
{
for(k=0;k<n;k++)
{
if(pos[k]==1)
{
s=k;
break;
}
}
KCEA Page 57
OPERATING SYSTEMS
}
fr[s]=seq[i];
for(k=0;k<n;k++)
printf("%d\t",fr[k]);
pf++;
printf("\n");
}
}
pfr=(float)pf/(float)max;
printf("\n The no. of page faults are %d", pf);
printf("\n Page fault rate %f", pfr);
getch();
}
int find max(int a[])
{
int max,i,k=0;
max=a[0]; for(i=0;i<n;i+
+)
{
if(max<a[i])
{
max=a[i];
k=i;
}
}
return k;
}
}
INPUT
Enter number of page references--10
Enter the reference string --123452525143
Enter the available no. of frames --- 3
OUTPUT
The Page Replacement Process is–
1 -1 -1 PFNo.1
1 2 -1 PFNo.2
1 2 3 PFNo.3
4 2 3 PFNo.4
5 2 3 PFNo.5
5 2 3
5 2 3
5 2 1 PFNo.6
5 2 4 PFNo.7
5 2 3 PFNo.8
KCEA Page 58
OPERATING SYSTEMS
KCEA Page 59