Cse (DS) 2-2 Os Lab Manual 2024-25 VR23
Cse (DS) 2-2 Os Lab Manual 2024-25 VR23
OPERATING SYSTEMS
LAB MANUAL
By
1
CONTENTS
S.No. PARTICULARS
3 PROGRAM OUTCOMES
6 LIST OF EXPERIMENTS
EACH EXPERIMENT WITH
I) AIM II) ALGORITHM III) PROGRAM IV) OUTPUT
7
VI) CONCLUSION
2
COLLEGE VISION
To evolve into a center of excellence in Science & Technology through creative and
innovative practices in teaching-learning, promoting academic achievement & research
excellence to produce internationally accepted competitive and world class professionals who are
psychologically strong and emotionally balanced imbued with social consciousness and ethical
values.
COLLEGE MISSION
To provide high quality academic programmers, training activities, research facilities and
opportunities supported by continuous industry-institute interaction aimed at employability,
entrepreneurship, leadership and research aptitude among students and contribute to the
economic and technological development of the region, state and nation.
To develop Data Science Professionals through creative and innovative approaches to address
the present and future challenges of the modern computing world
3
PROGRAM OUTCOMES (POs)
PO1.Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2.Problem analysis: Identify, formulate review research literature and analyze complex engineering
problems reaching substantiated conclusions using first principle of mathematics, natural science and
engineering science.
PO3.Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
PO4.Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5.Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding of the
limitations.
PO6.The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7.Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8.Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9.Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10.Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
PO11.Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one's own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12.Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
4
PROGRAM EDUCATIONAL OBJECTIVES (PEOs)
To create and sustain a community of learning in which students acquire knowledge and apply in
their concerned fields with due consideration for ethical, ecological, and economic issues.
To provide knowledge based services so as to meet the needs of the society and industry.
To make the students understand, design and implement the concepts in multiple arenas.
To educate the students in disseminating the research findings with good soft skills so as to become
successful entrepreneurs.
Professional Skills: Learn the basic concepts of Computer Science and Engineering and to apply
them to various areas, like Data Structures, Operating Systems, Computer Organization, Computer
Networks, Information Security etc., in the design and implementation of complex systems.
Problem-Solving Skills: Solutions to complex Computer Science and Engineering problems, using
latest hardware and software tools, along with analytical skills to arrive at cost effective and
appropriate solutions.
Entrepreneurship Skills and Career Management: Social- awareness & environmental-wisdom
along with ethical responsibility to lead a successful career and to sustain passion and zeal for real-
world applications using optimal resources as an Entrepreneur.
5
List of Experiments:
1. Write programs using the I/O system calls of UNIX/LINUX operating system (open, read, write, close,
3. Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention.
6
1) Write programs using the I/O system calls of UNIX/LINUX operating system (open, read,
write, close, fcntl, seek, stat, opendir, readdir)
7
Algorithm:
1. Starthe program.
2. OpenafileforO_RDWRforR/W,O_CREATEforcreatingafile,O_TRUNCfortruncate a file.
3. Usinggetchar(),readthecharacterandstored inthestring[]array.
4. Thestring[]arrayiswriteinto afilecloseit.
5. Then the first is opened for read onlymodeand read the characters and displayed itand
close the file.
6. Stop theprogram.
Program:
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
int main()
{
intn,i=0;
int f1,f2;
char c,strin[100]; f1=open("data",O_RDWR|O_CREAT|O_TRUNC);
while((c=getchar())!='\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
Conclusion:
8
a) Aim: C program using lseek
Lseek is a system call that is used to change the location of the read/write pointer of a file
descriptor. The location can be set either in absolute or relative terms.
Syntax: off_tlseek(intfildes,off_toffset,intwhence);
intfildes: The file descriptor of the pointer that is going to be moved.
off_t offset : The offset of the pointer (measured in bytes).
intwhence: Legal values for this variable are provided at the end which are:
SEEK_SET (Offset is to be measured in absolute terms),
SEEK_CUR (Offset is to be measured relative to the current location of the
pointer), SEEK_END (Offset is to be measured relative to the end of the file)
Algorithm:
1. Start the program
2. Open a file in read mode
3. Read the contents of the file
4. Use lseek to change the position of pointer in the read process
5. Stop
9
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:
Conclusion:
10
b) Aim: C program using opendir(),closedir(), readdir()
1. Creating directories.
Syntax:intmkdir(constchar*pathname,mode_tmode);
2. The ‘pathname’ argument is used for the name of the directory.
3. Opening directories
Syntax:DIR*opendir(constchar*name);
4. Reading directories.
Syntax:structdirent*readdir(DIR *dirp);
5. Removing directories.
Syntax:intrmdir(constchar*pathname);
6. Closing the directory.
Syntax:intclosedir(DIR *dirp);
Algorithm:
1. Start the program
2. Print a menu to choose the different directory operations
3. To create and remove a directory asks 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. Fit
does not exists print an error message.
5. Finally close the opened directory.
6. Stop
11
Program:
#include<stdio.h>
#include<fcntl.h>
#include<dirent.h>
main()
{
chard[10];intc,op;DIR*e;
struct dirent *sd;
printf("**menu**\n1.createdir\n2.removedir\n3.readdir\nenterurchoice");
scanf("%d",&op);
switch(op)
{
case1:printf("enterdirname\n");scanf("%s",&d);
c=mkdir(d,777);
if(c==1)
printf("dirisnotcreated");
else
printf("diris created"); break;
case2:printf("enterdirname\n");scanf("%s",&d);
c=rmdir(d);
if(c==1)
printf("dirisnotremoved");
else
printf("dirisremoved"); break;
case3:printf("enterdirnametoopen");
scanf("%s",&d);
e=opendir(d);
if(e==NULL)
printf("dirdoesnotexist");else
{
printf("direxist\n");while((sd=readdir(e))!=NULL)printf("%s\t",sd->d_name);
12
}
closedir(e);
break;
}
Output:
Conclusion:
13
2) Write C programs to simulate the following CPU Scheduling Algorithms:
a) FCFS
b) SJF
c) Round Robin
d) Priority
a) FCFS(FirstComeFirst Serve)
Aim:Write a C program to implement the various CPU Scheduling mechanisms such as FCFS
scheduling.
Algorithm:
6: Calculate
a. Averagewaitingtime =TotalwaitingTime/ Numberof process
b. AverageTurnaroundtime=TotalTurnaroundTime/Numberofprocess
14
Program:
#include<stdio.h>
intmain()
{
intbt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp; float avg_wt,avg_tat;
printf("Enter number of process:"); scanf("%d",&n);
printf("\nEnter Burst-Time:\n");
for(i=0;i<n;i++)
{
printf("p% d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[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]);
}
15
avg_tat=(float)total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage TurnaroundTime=%f\n",avg_tat);
}
Output:
Conclusion:
16
b) SJF (Shortest Job First)
Aim: Write a C program to implement the various process scheduling mechanisms such as SJF
Scheduling.
Algorithm:
3: For each process in the readyQ, assign the process-id and accept the CPU burst time
4: Start the ReadyQ according to the shortest Burst-time by sorting according to lowest to
highest burst time.
5: Set the waiting time of the first process as‘0’anditsturnaroundtimeasitsbursttime.
6: For each process in the ready queue, calculate
(a) Waitingtime for process(n)=waitingtime ofprocess (n-1)+Burst time ofprocess(n-1)
(b) TurnaroundtimeforProcess(n)=waitingtimeofProcess(n)+Burst timeforprocess(n)
7:Calculate
Average waiting time = Total waiting Time/ Number of processes
Average Turnaround time=Total Turnaround Time/Number of processes
8: Stop the process
17
Program:
#include<stdio.h>
intmain()
{
intbt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt, avg_tat;
printf("Enter number of Processes:");
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; //contains process number
}
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;
}
18
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
Output:
19
c) Round Robin Scheduling
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 readyQ and time-quantum (or) timeslice
3: For each process in the readyQ, assign the process-id and accept the CPU
burst-time.
4: Calculate the no. of time-slices for each process where, no. of time slice for
process(n)=burst time process(n)/time-slice.
5: If the burst-time is less than the time-slice, then the no. of time-slices=1.
7: Calculate
20
Program:
#include<stdio.h>
main()
int st[10],bt[10],wt[10],tat[10],n,tq;
inti,count=0,swt=0,stat=0,temp,sq=0;
float awt,atat;
printf("enterthenumberofprocesses");
scanf("%d",&n);
printf("enterthebursttimeofeachprocess/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;
21
if(st[i]>tq) st[i]=st[i]-tq;
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("processno\tbursttime\twaitingtime\tturnaroundtime\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("avgwttime=%f,avgturnaroundtime=%f",awt,atat);
}
22
Output:
Conclusion:
23
d) Priority Scheduling
Aim: Write a C program to implement the various process scheduling mechanisms
such as Priority Scheduling.
Algorithm:
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 turnaround time
6: For each process in the Ready Q calculate
(e) Waitingtime for process(n)=waitingtimeofprocess (n-1)+Burst time ofprocess(n-1)
(f) TurnaroundtimeforProcess(n)=waitingtimeofProcess(n)+Bursttimeforprocess(n)
7: Calculate
(g) Averagewaitingtime = Total waitingTime/ Numberof processes
(h) AverageTurnaroundtime=TotalTurnaroundTime/Numberofprocesses
8: Stop the process
24
Program:
#include<stdio.h>
intmain()
{
intbt[20],p[20],wt[20],tat[20],pri[20],i,j,k,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; //contains process number
}
p[i] =i;
//printf("Priority of Process");
printf("p%d ",i+1);
scanf("%d",&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];
bt[k]=temp;
temp=pri[i];
25
pri[i]=pri[k];
pri[k]=temp;
}
//calculate waiting-time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
26
Output:
Conclusion:
27
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:Ifmax[i,j]=k,Pi may request at-most k instances of 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
Work and Finish be the vector of length m and n respectively,
Work=Available and Finish[i] =False.
Find an “I” such that both
Finish[i] =False
Need<=Work
If no such I exist goto step-4.
work=work+Allocation,
Finish[i]=True;
IfFinish[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 restored.
28
Algorithm:
1. Start the program.
2. Get the values of resources and processes.
3. Get the available 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.
Else the system is not in safe state.
7. If the new request comes, then check that the system is in safe state or not, if we allow the
request.
8. Stop the program.
Program:
#include<stdio.h>
intmain ()
{
flag[i]=0;
}
29
printf("\nforprocess%d:",i);
for (j = 1; j <= rno; j++)
scanf("%d", &max[i][j]);
}
printf("\navailable 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
{
for(i =1; i <=pno; i++)
{
for(j =1; j <=rno;j++)
{
need[i][j] =max[i][j]-allocated[i][j];
}
}
printf ("\n Allocated matrix Max
need");
for (i = 1; i <= pno; i++)
{
printf ("\n");
for(j =1; j <=rno;j++)
{
printf("%4d", allocated[i][j]);
}
30
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;
for(i =1; i <=pno; i++)
{
if(flag[i] ==0)
{
prc=i;
work[j]+=allocated[prc][j];
allocated[prc][j] = 0;
max[prc][j]=0;
flag[prc]=1;
printf("%d",work[j]);
}
31
}
while(count !=pno&&prc!=0);
if(count==pno)
printf("\nThe system is in safe state!!");
else
printf("\nThe system is in an unsafe state!!");
return 0;
}
Output:
32
Conclusion: Programs Executed successfully for all possible cases of Input.
33
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 & 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>
intmax[10][10],alloc[10][10],need[10][10],avail[10],i,j,p,r,finish[10]={0},flag=0;
main( )
{
34
{
if(avail[j]<need[i][j])
avail[j]=need[i][j];
alloc[i][j]=0;
}
fun();
printf("\ndead lock is prevented by allocating needed resources");
printf("\nFailing: Hold & Wait condition");
for(j=0;j<r;j++)
{/*checking hold & wait condition*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}
fun();
printf("\nAVOIDING ANYONE OF THE CONDITION, U CAN PREVENT DEADLOCK");
}
fun()
{
while(1)
35
{
for(flag=0,i=0;i<p;i++)
{
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; } } }
Output:
36
Conclusion:
37
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.
Ifthereisemptyspaceinthebuffercheckthemutexvalueforenterintothecriticalsection. 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 by1.
iv) Consume the item.
5. Print the result.
38
Program:
#include<stdio.h>
#include<stdlib.h>
main ()
{
int n;
void producer ();
voidconsumer();
int wait (int);
intsignal(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("Buffer is full!!");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer ();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
39
}
return0;
}
intwait(int s)
{
return(--s);
}
intsignal(ints)
{
return(++s);
}
voidproducer ()
{
mutex=wait(mutex);
full = signal (full);
empty=wait(empty);
x++;
printf("\nProducer produces the item%d",x);
mutex = signal (mutex);
}
void consumer()
{
mutex=wait(mutex);
full = wait (full);
empty=signal(empty);
printf("\nConsumer consumes item%d",x); x--;
mutex=signal(mutex);
}
40
Output:
Conclusion:
41
5. Write C programs to illustrate the following IPC mechanisms 1) Pipes 2) FIFO 3) Message
Quene 4) Shared Memory
42
}
result=read(fd[0],recvd_msg,MSG_LEN);
if(result<0)
{ perror("read"); exit(3);
}
printf("%s\n",recvd_msg);return0;
}
a) FIFO
Program:
#include <stdio.h>
#include <stdlib.h>
#include<sys/stat.>
#include <unistd.h>
#include<linux/stat.h>
#defineFIFO_FILE "MYFIFO"
int main(void)
{
FILE *fp;
char readbuf[80];
/*Create the FIFO if it does not exist*/
umask(0);
mknod(FIFO_FILE,S_IFIFO|0666,0);
while(1)
{
fp=fopen(FIFO_FILE,"r");
fgets(readbuf, 80, fp);
printf("Received string:%s\n",readbuf);
fclose(fp);
}
return(0);
}
#include <stdio.h>
#include<stdlib.h>
#defineFIFO_FILE "MYFIFO"
intmain(intargc,char*argv[])
{
FILE *fp;
if(argc !=2) {
printf("USAGE:fifoclient[string]\n");
exit(1);
}
if((fp=fopen(FIFO_FILE,"w"))==NULL)
43
{ perror("fopen");
exit(1);
}
fputs(argv[1], fp);
fclose(fp);
return(0);
}
//structureformessagequeue
struct mesg_buffer {
long
msg_type;charmsg_text[100];
} message;
int main()
{
key_tkey;
int msgid;
//ftoktogenerateuniquekey
key = ftok("progfile", 65);
//msgget creates a message-queue and returns identifier
msgid=msgget(key,0666|IPC_CREAT);
message.mesg_type = 1;
printf("Write Data : ");
gets(message.mesg_text);
//msg snd to send message
msgsnd(msgid,&message,sizeof(message),0);
//display the message
printf("Datasendis: %s\n",message.mesg_text);
return0;
}
44
C Program for Message-Queue (Reader Process)
#include <stdio.h>
#include <sys/ipc.h>
#include<sys/msg.h>
//structureformessagequeue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_tkey;
int
msgid;
//ftok to generate unique key
key = ftok("progfile", 65);
//msgget creates a message-queue and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
//msgrcvtoreceivemessage
msgrcv(msgid, &message,sizeof(message),1, 0);
// display the message
printf("DataReceivedis:%s\n",
message.mesg_text);
// to destroy the message queue
msgctl(msgid,IPC_RMID,NULL);
return0;
}
#include <stdio.h>
#include<sys/ipc.h>
#include<sys/msg.h>
//structure for message queue
struct mesg_buffer {
long mesg_type;charmesg_text[100];
} message;
45
int main()
{
key_tkey;
int msgid;
//ftok to generate unique key
key = ftok("progfile", 65);
//msgget creates a message-queue and returns identifier
msgid=msgget(key,0666|IPC_CREAT);
//msgrcv to receive message
msgrcv(msgid, &message,sizeof(message),1, 0);
// display the message
printf("DataReceivedis:%s\n", message.mesg_text);
// to destroy the message queue
msgctl(msgid,IPC_RMID,NULL);
return0;
}
Output:
46
47
6. Write C programs to simulate the following Memory Management Techniques:
a) Paging
ALGORITHM:
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];
printf("\nEnter the memory size -- ");
scanf("%d",&ms);
printf("\nEnter the pagesize--");
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("\nEnterno.ofpagesrequiredforp[%d]--",i);
scanf("%d",&s[i]);
if(s[i]>rempages)
{
printf("\nMemoryisFull"); break;
}
rempages = rempages - s[i];
printf("\nEnter page table 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 page number and offset -- ");
scanf("%d %d %d",&x,&y, &offset);
if(x>np||y>=s[i]||offset>=ps)
printf("\nInvalid Processor Page Number or offset");
48
else
{
pa=fno[x][y]*ps+offset;
printf("\nThePhysicalAddressis-- %d",pa);
}
getch();
}
Output:
Conclusion:
49
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. Step5:
Read the segment number and displacement.
Step6: If the segment number and displacement is valid, compute the physical address and display the
same.
Program:
Program:
#include<stdio.h>
#include<conio.h>
struct list
{
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”)
50
}
q->next=malloc(sizeof(Structlist)); q-
>next ->limit=limit;
q->next->base=base; q-
>next ->seg=seg;
q->next->next=NULL;
}
}
intfind(struct list*q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->limit;
}
intsearch(structlist*q,intseg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->base;
}
main()
{
p=NULL;
intseg,offset,limit,base,c,s,physical;
printf(“Enter segment table/n”);
printf(“Enter-1assegmentvaluefortermination\n”); do
{
printf(“Entersegmentnumber”);
scanf(“%d”,&seg);
if(seg!=-1)
{
printf(“Enterbasevalue:”);
scanf(“%d”,&base);
printf(“Entervalueforlimit:”);
scanf(“%d”,&limit);
insert(p,base,lmit,seg);
}
}
while(seg!=-1)
printf(“Enteroffset:”);
scanf(“%d”,&offset);
printf(“Enterbsegmentationnumber:”);
scanf(“%d”,&seg);
c=find(p,seg);
s=search(p,seg); if(offset<c)
{
physical=s+offset;
51
printf(“Addressinphysicalmemory%d\n”,physical);
}
else
{
printf(“error”);
}
Output:
Entersegment table
Enter-1assegmentationvaluefortermination Enter
segment number:1
Enter base value:2000
Entervalueforlimit:100
Entersegmentnumber:2 Enter
base value:2500
Entervalueforlimit:100
Entersegmentationnumber:-1
Enter offset:90
Entersegment number:2
Addressinphysicalmemory2590
Entersegment table
Enter-1assegmentationvaluefortermination Enter
segment number:1
Enter base value:2000
Entervalueforlimit:100
Entersegmentnumber:2 Enter
base value:2500
Entervalueforlimit:100
Entersegmentationnumber:-1
Enter offset:90
Enter segment number:1
Addressinphysicalmemory20
Conclusion:
52
7) Write C programs to simulate Page replacement policies a) FCFS b) LRU c) Optimal
a) FCFS
Program:
#include<stdio.h>
#include<conio.h>
intfr[3];
void main()
{
voiddisplay();
int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};
int flag1=0,flag2=0,pf=0,frsize=3,top=0;
clrscr();
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0;flag2=0; for(i=0;i<12;i++)
{
if(fr[i]==page[j])
{
flag1=1;flag2=1; break;
}
}
if(flag1==0)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];flag2=1;break;
}
}
}
if(flag2==0)
53
{
fr[top]=page[j];
top++;
pf++;
if(top>=frsize)
top=0;
}
display();
}
printf("Number of pagefaults:%d",pf+frsize);
getch();
}
Void display()
{
int i;
printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}
Output:
2-1-1
23-1
23-1
231
531
521
524
524
324
324
354
352
Number of page faults:9
Conclusion:
54
b) LRU
Program:
#include<stdio.h>
#include<conio.h
>int fr[3];
void main()
{
voiddisplay();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
intindex,k,l,flag1=0,flag2=0,pf=0,frsize=3;
clrscr();
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0,flag2=0;
for(i=0;i<3;i++)
{
if(fr[i]==p[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];flag2=1;
break;
}
}
}
55
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-j;
break;
}
}
for(i=0;i<3;i++)
{
if(fs[i]==0)
index=i;
}
fr[index]=p[j];
pf++;
}
display();
}
printf("\nnoofpagefaults:%d",pf+frsize);
getch();
}
void display()
{
int i; printf("\n");
for(i=0;i<3;i++)
printf("\t%d", fr[i]);
}
Output:
2-1-1
23-1
23-1
231
251
251
254
254
354
352
352
352
No of page faults:7
Conclusion:
Program:
#include<stdio.h>
#include<conio.h
>int fr[3], n,
m;void
display();
voidmain()
{
inti,j,page[20],fs[10];
int max,found=0,lg[3],index,k,l,flag1=0,
flag2=0,pf=0; float pr;
clrscr();
printf("Enter length of the reference string:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter no of frames:");
scanf("%d",&m);
for(i=0;i<m;i++
) fr[i]=-1;
pf=m;
for(j=0;j<n;j++)
{
flag1=0;flag2=0;
for(i=0;i<m;i++)
{
if(fr[i]==page[j])
{
flag1=1;flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
57
fr[i]=page[j];flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-
j; break;
}
}
}
found=0;
for(i=0;i<m;i++)
{
if(lg[i]==0)
{
index=i;
found=1;
break;
}
}
if(found==0)
{
max=lg[0];
index=0;
for(i=0;i<m;i++)
{
if(max<lg[i])
{
max=lg[i];
index=i;
}
}
}
fr[index]=page[j];
pf++;
}
display();
}
printf("Number of page faults : %d\n", pf); pr=(float)pf/n*100;
printf("Pagefaultrate=%f\n",pr);getch();
}
void display()
{
int i;
58
for(i=0;i<m;i++)
printf("%d\t",fr[i]);
printf("\n");
}
for(j=0;j<n;j++)
{
flag1=0;flag2=0;
for(i=0;i<m;i++)
{
if(fr[i]==page[j])
{
flag1=1;flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-
j; break;
}
}
}
found=0;
for(i=0;i<m;i++)
{
if(lg[i]==0)
{
index=i;
found=1;
break;
}
}
if(found==0)
{
max=lg[0];
59
index=0;
for(i=0;i<m;i++)
{
if(max<lg[i])
{
max=lg[i];
index=i;
}
}
}
fr[index]=page[j];
pf++;
}
display();
}
printf("Number of page faults : %d\n", pf); pr=(float)pf/n*100;
printf("Pagefaultrate=%f\n",pr);getch();
}
voiddisplay()
{
int i;
for(i=0;i<m;i++)
printf("%d\t",fr[i]);
printf("\n");
}
Output:
Enter length of the reference string: 12
Enter the reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Enter no of frames: 3
1-1-1
12-1
123
124
124
124
125
125
125
325
425
425
Number of page faults: 7 Page fault rate=58.333332
Conclusion:
Programs Executed successfully for all possible cases of Input.
60
8) Write C programs to simulate File Allocation methods
Aim: To write Programs to simulate File Allocation methods
Algorithm:
Step 1: Start the program.
Step 2: Get the number of memory partition and their sizes.
Step 3: Get the number of processes and values of block size for each process.
Step 4: First fit algorithm searches all the entire memory block until a hole which is big enough is encountered. It
allocates that memory block for the requesting process.
Step 5: Best-fit algorithm searches the memory blocks for the smallest hole which can be allocated to requesting
process and allocates it.
Step 6: Worst fit algorithm searches the memory blocks for the largest hole and allocates it to the process.
Step 7: Analyses all the three memory management techniques and display the best algorithm which utilizes the
memory resources effectively and efficiently.
Step 8: Stop the program.
Program:
61
exit();
getch();
}
Output:
Conclusion:
62