Os Lab Manual
Os Lab Manual
LABMANUAL
OPERATINGSYSTEMSLABSYLLABUS
1 WriteaCprogramsimulatethefollowingCPUscheduling algorithms:
a)FCFS b)SJF c)RoundRobin d)Priority
2 Writeprogramsusing theI/O systemcallsofUNIX/LINUXoperatingsystem.
3 WriteaCprogramtosimulateBankersAlgorithmforDeadlockAvoidanceand Prevention
[Link] 1
EXPERIMENT-1
WriteaCprogramsimulatethefollowingCPUschedulingalgorithms:
a)FCFS b)SJF c)RoundRobin d)Priority
a)FCFS
DESCRIPTION
Assumealltheprocessesarriveat thesametime.
FCFSCPUSCHEDULINGALGORITHM
For FCFS scheduling algorithm, read the number of processes/jobs in the system, their CPU burst
times. The cheduling is performed on the basis of arrival time of the processes irrespective of their
other parameters. Each process will be executed according to its arrivaltime. Calculate the waiting
time and turnaround time of each of the processes accordingly.
CPUSCHEDULING
0 24 27 30
Waitingtime for P1=0;P2=24;P3=27
Average waiting time: (0 + 24 + 27)/3 = 17
[Link] 2
ALGORITHM
1. Start
2. Declarethearraysize
3. Readthenumberofprocessestobeinserted
4. ReadtheBurst timesofprocesses
5. calculatethewaitingtimeofeachprocess
wt[i+1]=bt[i]+wt[i]
6. calculatetheturnaroundtimeofeachprocess
tt[i+1]=tt[i]+bt[i+1]
7. Calculatetheaveragewaitingtimeandaverageturnaroundtime.
8. Displaythe values
9. Stop
PROGRAM:
#include<stdio.h>voi
d main()
{
inti,j,bt[10],n,wt[10],tt[10],w1=0,t1=0;
float aw,at;
printf("[Link]:\n");
scanf("%d",&n);
printf("enterthebursttimeofprocesses:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
for(i=0;i<n;i++)
{ wt[0]=
0;
tt[0]=bt[0];
wt[i+1]=bt[i]+wt[i];
tt[i+1]=tt[i]+bt[i+1];
w1=w1+wt[i];
t1=t1+tt[i];
}
aw=w1/n;
at=t1/n;
printf("\nbt\twt\ttt\n");
for(i=0;i<n;i++)
printf("%d\t%d\t%d\n",bt[i],wt[i],tt[i]); printf("aw=%f\n,at=%f\
n",aw,at);
}
[Link] 3
INPUT
Enternoofprocesses 3
enterbursttime
12
8
20
EXPECTEDOUTPUT
btwttt
12012
81220
20 20 40
aw=10.666670
at=24.00000
b) SJF
SJFCPUSCHEDULINGALGORITHM
ForSJFschedulingalgorithm,readthenumberofprocesses/jobsinthesystem,theirCPUbursttimes.
Arrange all the jobs in order withrespect to their burst times. There may be two jobs in queue with
thesameexecutiontime,[Link]
[Link] of the
processes accordingly.
HARDWAREREQUIREMENTS:IntelbasedDesktopPc
RAMof512MB
SOFTWAREREQUIREMENTS:
TurboC/BorlandC.
THEORY:
ExampleofNonPreemptiveSJF
P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 3.0 4
[Link] 4
P1 P3 P2 P4
0 7 8 12 16
ExampleofPreemptiveSJF
P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 3.0 4
P1 P2 P3 P2 P4 P1
Averagewaitingtime=(9+1+0+2)/4=3 ALGORITHM
1. Start
2. Declarethearraysize
3. Readthenumberofprocessestobeinserted
4. ReadtheBurst timesofprocesses
5. sorttheBursttimes inascendingorderandprocesswithshortestbursttimeis firstexecuted.
6. calculatethewaitingtimeofeachprocess
wt[i+1]=bt[i]+wt[i]
7. calculatetheturnaroundtimeofeachprocess
tt[i+1]=tt[i]+bt[i+1]
8. Calculatetheaveragewaitingtimeandaverageturnaroundtime.
9. Displaythe values
10. Stop
PROGRAM:
#include<stdio.h>voi
d main()
{
inti,j,bt[10],t,n,wt[10],tt[10],w1=0,t1=0;
float aw,at;
printf("[Link]:\n");
scanf("%d",&n);
printf("enterthebursttimeofprocesses:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
for(i=0;i<n;i++)
{
[Link] 5
for(j=i;j<n;j++)
if(bt[i]>bt[j])
{
t=bt[i];
bt[i]=bt[j];
bt[j]=t;
}
}
for(i=0;i<n;i++)
printf("%d",bt[i]);
for(i=0;i<n;i++)
{ wt[0]=
0;
tt[0]=bt[0];
wt[i+1]=bt[i]+wt[i];
tt[i+1]=tt[i]+bt[i+1];
w1=w1+wt[i];
t1=t1+tt[i];
}
aw=w1/n;
at=t1/n;
printf("\nbt\twt\ttt\n");
for(i=0;i<n;i++)
printf("%d\t%d\t%d\n",bt[i],wt[i],tt[i]); printf("aw=%f\n,at=%f\
n",aw,at);
}
INPUT:
enternoofprocesses 3
enterbursttime
12
8
20
OUTPUT:
bt wt tt
12820
808
202040
aw=9.33
at=22.64
[Link] 6
c) RoundRobin
DESCRIPTION
Assumealltheprocessesarriveat thesametime.
ROUNDROBINCPUSCHEDULING ALGORITHM
For round robin scheduling algorithm, read the number of processes/jobs in the system, their CPU
burst times, and the size ofthetime slice. Time slicesare assigned to eachprocess inequalportions and
in circular order, handling all processes execution. This allows every process to get an equal
chance. Calculate the waiting time and turnaround time of each of the processes accordingly.
HARDWAREREQUIREMENTS:IntelbasedDesktopPcRAMof512MB
SOFTWAREREQUIREMENTS:TurboC/BorlandC.
THEORY:
RoundRobin:
ExampleofRRwith timequantum=3
Process Bursttime
aaa 4
Bbb 3
Ccc 2
Ddd 5
Eee 1
ALGORITHM
1. Start
2. Declarethearraysize
3. Readthenumberofprocessestobeinserted
4. Readthe burst timesofthe processes
5. ReadtheTimeQuantum
6. ifthe bursttimeofaprocess isgreaterthantimeQuantumthensubtracttimequantumformthe burst
time
Else
Assignthebursttimetotime quantum.
[Link] turnaround timeoftheprocesses.
8. Displaythe values
9. Stop
[Link] 7
PROGRAM:
#include<stdio.h>voi
d main()
{
int st[10],bt[10],wt[10],tat[10],n,tq;
inti,count=0,swt=0,stat=0,temp,sq=0;
float awt=0.0,atat=0.0;
printf("Enternumberofprocesses:");
scanf("%d",&n);
printf("Enterbursttimeforsequences:");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
st[i]=bt[i];
}
printf("Entertimequantum:");
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;
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];
[Link] 8
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("Process_noBursttimeWaittimeTurnaroundtime");
for(i=0;i<n;i++)
printf("\n%d\t %d\t%d\t%d",i+1,bt[i],wt[i],tat[i]);
printf("\nAvgwaittimeis%fAvgturnaroundtimeis %f",awt,atat);
}
Input:
Enternoofjobs 4
Enterbursttime
5
12
8
20
Output:
Btwttt
505
12513
81325
20 25 45
aw=10.75000
at=22.000000
[Link] 9
d) Priority
HARDWAREREQUIREMENTS:Intelbased DesktopPc
RAMof512MB
SOFTWAREREQUIREMENTS:
TurboC/BorlandC.
THEORY:
InPriorityScheduling, eachprocess isgivenapriority, andhigherprioritymethodsareexecuted first,
while equal priorities are executed First Come First Servedor Round Robin.
Thereareseveralwaysthatprioritiescanbe assigned:
Internalprioritiesareassignedbytechnicalquantitiessuchasmemoryusage,and file/IO
operations.
Externalprioritiesareassignedbypolitics,commerce,oruserpreference,suchas
importanceandamount beingpaid forprocessaccess(the latterusuallybeing for
mainframes).
ALGORITHM
1. Start
2. Declarethearraysize
3. Readthenumberofprocessestobeinserted
4. ReadthePrioritiesofprocesses
5. sorttheprioritiesandBursttimesinascending order
5. calculatethewaitingtimeofeachprocess
wt[i+1]=bt[i]+wt[i]
6. calculatetheturnaroundtimeofeachprocess
tt[i+1]=tt[i]+bt[i+1]
7. Calculatetheaveragewaitingtimeandaverageturnaroundtime.
8. Displaythe values
9. Stop
[Link] 10
PROGRAM:
#include<stdio.h>voi
d main()
{
int i,j,pno[10],prior[10],bt[10],n,wt[10],tt[10],w1=0,t1=0,s;
float aw,at;
printf("enterthenumberofprocesses:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("The process %d:\n",i+1);
printf("Enterthebursttimeofprocesses:");
scanf("%d",&bt[i]);
printf("Enterthepriorityofprocesses%d:",i+1);
scanf("%d",&prior[i]);
pno[i]=i+1;
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(prior[i]<prior[j])
{
s=prior[i];
prior[i]=prior[j];
prior[j]=s;
s=bt[i];
bt[i]=bt[j];
bt[j]=s;
s=pno[i];
pno[i]=pno[j];
pno[j]=s;
}
}
}
for(i=0;i<n;i++)
{
wt[0]=0;
tt[0]=bt[0];
wt[i+1]=bt[i]+wt[i];
tt[i+1]=tt[i]+bt[i+1];
w1=w1+wt[i];
t1=t1+tt[i];
aw=w1/n;
[Link] 11
at=t1/n;
}
printf("\njob\t bt\twt \ttat\t prior\n"); for(i=0;i<n;i+
+)
printf("%d\t%d\t%d\t%d\t%d\n",pno[i],bt[i],wt[i],tt[i],prior[i]);
printf("aw=%f \t at=%f \n",aw,at);
Input:
Enternoofjobs 4
Enterbursttime
10
2
4
7
Enterpriorityvalues 4
2
1
3
Output:
Btprioritywttt 4
104
2246
73613
10 4 13 23
aw=5.750000
at=12.500000
[Link] 12
EXPERIMENT-2
Objective:
PROGRAM:
#include<unistd.h>
#include <fcntl.h>
#include<string.h>
#include <stdio.h>
int main()
{
int fd[2];
charbuf1[25]=“justatest\n”; char
buf2[100];
fd[0] = open(“tfile”,O_RDWR);
fd[1] = open(“tfile”,O_RDWR);
write(fd[0],buf1,strlen(buf1));
printf(“\nEnteryourtextnow…”);
gets(buf1);
write(fd[0],buf1,strlen(buf1));
write(1,buf2,read(fd[1],buf2,sizeof(buf2)));
close(fd[0]);
close(fd[1]);
printf(“\n”);
return 0;
}
[Link] 13
EXPERIMENT-3
WriteaCprogramtosimulateBankersAlgorithmforDeadlockAvoidance andPrevention
OBJECTIVE
WriteaCprogramto simulateBankersAlgorithmfor Deadlock Avoidance
DESCRIPTION
Inamultiprogrammingenvironment,severalprocessesmaycompeteforafinitenumberofresources. A
process requests resources; if the resources are not available at that time, the process enters a
[Link],awaitingprocessisneveragainabletochangestate,becausetheresources it has
requested are 4held by other waiting processes. This situation is called a deadlock. Deadlock
avoidance isoneofthetechniques forhandlingdeadlocks. Thisapproachrequiresthattheoperating
systembegiveninadvanceadditionalinformationconcerningwhichresourcesaprocesswillrequest
[Link], itcandecideforeachrequestwhetheror
[Link], the
systemmust consider the resources currentlyavailable, the resources currentlyallocatedto each
process, and the future requests and releases of each process.
Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system with multiple
instances of each resource type.
NAMEOFEXPERIMENT:SimulateBanker’sAlgorithmforDeadlockAvoidance.
AIM: Simulate Banker’s Algorithm for Deadlock Avoidance to find whether the systemis insafe
state or not.
HARDWAREREQUIREMENTS:Intelbased DesktopPc
RAM of 512 MB
SOFTWAREREQUIREMENTS:TurboC/BorlandC. THEORY:
DEADLOCKAVOIDANCE
Toimplementdeadlockavoidance&PreventionbyusingBanker’sAlgorithm.
Banker’sAlgorithm:
When a new process enters a system, it must declare the maximum number of instances of
each resourcetype it needed. This number mayexceed the totalnumber ofresources in the system.
When the user request a set ofresources, the system must determine whether the allocation ofeach
resources will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.
Datastructures
n-Numberofprocess,m-numberofresourcetypes.
Available:Available[j]=k, k–instanceofresourcetypeRjisavailable.
Max:Ifmax[i,j]=k, PimayrequestatmostkinstancesresourceRj.
Allocation:IfAllocation[i,j]=k,Piallocatedto kinstancesofresource Rj
Need:IfNeed[I,j]=k,Pimay needkmoreinstancesofresourcetypeRj,
[Link] 14
Need[I,j]=Max[I,j]-Allocation[I,j];
Safety Algorithm
1. WorkandFinishbethevectoroflengthmand nrespectively, Work=Availableand
Finish[i] =False.
2. Findanisuchthatboth
Finish[i]=False
Need<=Work
IfnosuchIexistsgotostep4.
3. work=work+Allocation,Finish[i]=True;
4. ifFinish[1]=TrueforallI,thenthesystemisinsafestate.
Resourcerequestalgorithm
Let Request iberequest vector fortheprocessPi, Ifrequest i=[j]=k, thenprocessPiwantsk
instances of resource type Rj.
1. ifRequest<=[Link] anerrorcondition.
2. ifRequest<=Availablego to [Link].
3. HavethesystempretendtohaveallocatedtherequestedresourcestoprocessPibymodifying the
state as follows;
Available=Available-Request I;
AllocationI=Allocation+RequestI;
Need i=Need i-Request I;
Iftheresultingresourceallocationstateissafe, thetransactioniscompletedandprocessPiisallocated its
resources. However if the state is unsafe, the Pi must wait for Request i and the old resource-
allocation state is restored.
ALGORITHM:
1. Starttheprogram.
2. Getthevaluesofresourcesandprocesses.
3. Gettheavailvalue.
4. Afterallocationfindtheneed value.
5. Checkwhetheritspossibletoallocate.
6. Ifitispossiblethenthesystemis insafe state.
7. Elsesystemisnot insafetystate.
8. Ifthenewrequestcomesthencheck thatthesystemisinsafety.
9. ornotifweallowtherequest.
10. stoptheprogram.
[Link] 15
PROGRAM:
#include<stdio.h>str
uct da {
intmax[10],al[10],need[10],before[10],after[10];
}p[10];
voidmain(){
inti,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0;
printf("\n Enter the no of processes:");
scanf("%d",&n);
printf("\nEnterthenoofresources:");
scanf("%d",&r);
for(i=0;i<n;i++)
{ printf("process%d\
n",i+1); for(j=0;j<r;j++) {
printf("maximumvalueforresource%d:",j+1);
scanf("%d",&p[i].max[j]);
}
for(j=0;j<r;j++){
printf("allocatedfromresource%d:",j+1);
scanf("%d",&p[i].al[j]);
p[i].need[j]=p[i].max[j]-p[i].al[j];
}
}
for(i=0;i<r;i++){
printf("Entertotalvalueofresource%d:",i+1);
scanf("%d",&tot[i]);
}
for(i=0;i<r;i++) {
for(j=0;j<n;j++)
temp=temp+p[j].al[i];
av[i]=tot[i]-temp;
temp=0;
}
printf("\n\tmaxallocatedneededtotalavail"); for(i=0;i<n;i++)
{
printf("\n P%d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].max[j]);
printf("\t"); for(j=0;j<r;j+
+) printf("%d",p[i].al[j]);
printf("\t"); for(j=0;j<r;j+
+)
printf("%d",p[i].need[j]);
printf("\t"); for(j=0;j<r;j+
+)
{
[Link] 16
if(i==0)
printf("%d",tot[j]);
}
printf("");
for(j=0;j<r;j++) {
if(i==0)
printf("%d",av[j]);
}
}
printf("\n\n\tAVAILBEFORE\tAVAILAFTER"); for(l=0;l<n;l++)
{
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
if(p[i].need[j]>av[j])
cn++;
if(p[i].max[j]==0)
cz++;
}
if(cn==0&&cz!=r)
{
for(j=0;j<r;j++)
{
p[i].before[j]=av[j]-p[i].need[j];
p[i].after[j]=p[i].before[j]+p[i].max[j];
av[j]=p[i].after[j];
p[i].max[j]=0;
}
printf("\n p%d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].before[j]);
printf("\t");for(j=0;j<r;j++)
printf("%d",p[i].after[j]);
cn=0;
cz=0; c+
+;
break;
}
else {
cn=0;cz=0;
}
}
}
if(c==n)
[Link] 17
printf("\ntheabovesequenceisasafesequence"); else
printf("\ndeadlockoccured");
}
OUTPUT:
//TESTCASE 1:
[Link]
[Link]
PROCESS 1
MAXIMUMVALUEFORRESOURCE1:3
MAXIMUMVALUEFORRESOURCE2:2
MAXIMUMVALUEFORRESOURCE3:2
ALLOCATED FROM RESOURCE 1:1
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:0
PROCESS 2
MAXIMUMVALUEFORRESOURCE1:6
MAXIMUMVALUEFORRESOURCE2:1
MAXIMUMVALUEFORRESOURCE3:3
ALLOCATED FROM RESOURCE 1:5
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 3
MAXIMUMVALUEFORRESOURCE1:3
MAXIMUMVALUEFORRESOURCE2:1
MAXIMUMVALUEFORRESOURCE3:4
ALLOCATED FROM RESOURCE 1:2
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS4
MAXIMUM VALUE FOR RESOURCE 1:4
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:0
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:2
ENTERTOTALVALUEOFRESOURCE1:9
ENTERTOTALVALUEOFRESOURCE2:3
[Link] 18
ENTERTOTALVALUEOFRESOURCE3:6
RESOURCESALLOCATEDNEEDED TOTALAVAIL
P1 322 100 222 936 112
P2 613 511 102
P3 314 211 103
P4 422 002 420
AVAILBEFOREAVAILAFTER
P2 010 623
P1 401 723
P3 620 934
P4 514 936
THEABOVESEQUENCEISASAFE SEQUENCE
OBJECTIVE
WriteaCprogramto simulateBankersalgorithmforDeadlockPrevention
DESCRIPTION
Inamultiprogrammingenvironment,severalprocessesmaycompeteforafinitenumberofresources. A
process requests resources; if the resources are not available at that time, the process enters a
[Link],awaitingprocessisneveragainabletochangestate,becausetheresources it has
requested are held by other waiting processes. This situation is called a deadlock. Deadlock
avoidance isoneofthetechniques forhandlingdeadlocks. Thisapproachrequiresthattheoperating
systembegiveninadvanceadditionalinformationconcerningwhichresourcesaprocesswillrequest
[Link], itcandecideforeachrequestwhetheror
[Link], the
systemmust consider the resources currentlyavailable, the resources currentlyallocatedto each
process, and the future requests and releases of each process.
Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system with multiple
instances of each resource type.
NAMEOFEXPERIMENT:SimulateAlgorithmforDeadlockprevention. AIM:
Simulate Algorithm for Deadlock prevention .
HARDWAREREQUIREMENTS:Intelbased DesktopPc
RAMof512MB
SOFTWAREREQUIREMENTS:TurboC/BorlandC.
[Link] 19
THEORY:
DeadlockDefinition:
A set of processes is deadlocked if each process in the set is waiting for an event that only another
process in the set can cause (including itself).Waiting for an event could be:
waitingforaccesstoacriticalsection
waitingforaresourceNotethatitisusuallyanon-preemptable (resource).
ConditionsforDeadlock :
•Mutualexclusion:resourcescannotbe shared.
•Holdandwait:processesrequestresourcesincrementally,andholdonto
What they've got.
•Nopreemption:resourcescannotbeforcibly takenfromprocesses.
•Circularwait:circularchainofwaiting, inwhicheachprocessiswaiting fora
resource held by the next process in the chain.
StrategiesfordealingwithDeadlock:
• ignoretheproblemaltogether
•detectionandrecovery
•avoidancebycarefulresource allocation
•preventionbystructurally negatingoneofthefournecessaryconditions.
DeadlockPrevention:
Difference from avoidance is that here, the system itself is built in such a way that there are no
deadlocks. Make sure atleast one ofthe 4 deadlock conditions is never satisfied. This may however
be even more conservative than deadlock avoidance strategy.
Algorithm:
1. Start
2. AttackingMutexcondition:[Link]
resources.
3. Attackingpreemption: notsomethingyouwanttodo.
4. Attacking holdandwait condition: makeaprocess holdatthe most 1resourceat [Link] the
requests at the beginning. All or nothing policy. If you feel,retry. eg. 2-phase locking
5. Attackingcircularwait:[Link]
ordersothattherearenocyclespresent intheresourcegraph.Resourcesnumbered1...[Link]
[Link] you may
be holding.
6. Stop
PROGRAM:
[Link] 20
#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\nSIMULATIONOFDEADLOCKPREVENTION");
printf("Enter no. of processes, resources"); scanf("%d
%d",&p,&r);printf("Enterallocationmatrix"); for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&alloc[i][j]);
printf("entermaxmatrix");
for(i=0;i<p;i++)/*readingthemaximummatrixandavailalematrix*/ for(j=0;j<r;j++)
scanf("%d",&max[i][j]);
printf("enteravailablematrix");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
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)
{i f(finish[i]!
=1)
{
printf("\n\nFailing:Mutualexclusion");
for(j=0;j<r;j++)
{/*checkingformutualexclusion*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}fun();
printf("\nByallocatingrequiredresourcesto process%ddeadlock isprevented",i); printf("\n\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\ndaedlockispreventedbyallocatingneededresources");
printf(" \n \n failing:Hold and Wait condition ");
for(j=0;j<r;j++)
{/*checkingholdandwaitcondition*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}
fun();
[Link] 21
printf("\nAVOIDINGANYONEOFTHECONDITION,UCANPREVENTDEADLOCK");
}
}
}
fun()
{
while(1)
{
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;
elsebreak;
}
if(j==r)
{
for(j=0;j<r;j++)
avail[j]+=alloc[i][j];
flag=1;
finish[i]=1;
}
}
}
if(flag==0)
break;
}
}
Output:
SIMULATIONOFDEADLOCKPREVENTION
[Link],resources3,2
enter allocation matrix 2 4 5
345
Entermaxmatrix434
561
Enteravailablematrix2
5
Failing : MutualExclusion
byallocatingrequiredresourcestoprocessdeadisprevented
Lackofnopreemptiondeadlockis prevented byallocating needed resources
Failing : Hold and Wait condition
[Link] 22
EXPERIMENT-4
OBJECTIVE
DESCRIPTION
[Link]
processes, producerand consumer, who share a fixed size buffer. Producerworkisto produce data
oritems and put in buffer. Consumer work is to remove data frombuffer and consume it. We have
tomakesurethatproducerdonotproducedatawhenbufferisfullandconsumerdonotremovedata when
buffer is empty.
The producer should go to sleep when buffer is full. Next time when consumer removes data it
notifies the producer and producer starts producing data again. The consumer should go to sleep
when buffer is empty. Next time when producer add data it notifies the consumer and consumer
starts consuming data. This solution can be achieved using semaphores.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
intmutex=1,full=0,empty=3,x=0;
int main()
{
intn;
void producer();
voidconsumer();
int wait(int);
int signal(int); printf("\[Link]\
[Link]\[Link]"); while(1)
{
printf("\nEnteryourchoice:");
scanf("%d",&n);
switch(n)
{
case1:if((mutex==1)&&(empty!=0))
[Link] 23
producer();
else
printf("Bufferisfull!!");
break;
case2:if((mutex==1)&&(full!=0))
consumer();
else
printf("Bufferisempty!!");
break;
case3:
exit(0);
break;
}
}
return0;
}
intwait(ints)
{
return(--s);
}
intsignal(int s)
{
return(++s);
}
voidproducer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducerproducestheitem%d",x);
mutex=signal(mutex);
}
voidconsumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumerconsumesitem%d",x);
x--;
mutex=signal(mutex);
[Link] 24
}
[Link] 25
Output
1. Producer
2. Consumer
3. Exit
Enter your choice:1
Producerproducestheitem1 Enter
your choice:2
Consumerconsumesitem1
Enter your choice:2
Buffer is empty!!
Enteryourchoice:1
Producerproducestheitem1 Enter
your choice:1
Producerproducestheitem2 Enter
your choice:1
Producerproducestheitem3 Enter
your choice:1
Buffer is full!!
Enteryourchoice:3
[Link] 26
EXPERIMENT-5
WriteaCprogramto illustratethefollowing IPCmechanisms
a) Pipes b) FIFOs c)MessageQueues d)Shared Memory
OBJECTIVE:
Write a CprogramtoillustratethePipesIPCmechanism
PROGRAM
#include <stdio.h>
#include <unistd.h>
#defineMSGSIZE16
char*msg1="hello,world#1";
char*msg2="hello,world#2";
char*msg3="hello,world#3";
int main()
{
charinbuf[MSGSIZE];
int p[2], i;
if(pipe(p)<0)
exit(1);
/*continued*/
/*writepipe*/
write(p[1],msg1,MSGSIZE);
write(p[1],msg2,MSGSIZE);
write(p[1],msg3,MSGSIZE);
hello,world#1
hello,world#2
hello,world#3
[Link] 27
OBJECTIVE
b) Write a CprogramtoillustratetheFIFOIPC mechanism
PROGRAM
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include<sys/types.h>
#include <unistd.h>
int main()
{
intfd;
//FIFO filepath
char*myfifo="/tmp/myfifo";
//Creatingthenamedfile(FIFO)
//mkfifo(<pathname>,<permission>)
mkfifo(myfifo, 0666);
chararr1[80],arr2[80];
while (1)
{
//OpenFIFOforwriteonly
fd=open(myfifo,O_WRONLY);
//Takeaninputarr2ingfromuser.
//80ismaximumlength fgets(arr2,
80, stdin);
//Writetheinputarr2ingonFIFO
//andcloseit
write(fd,arr2,strlen(arr2)+1); close(fd);
//OpenFIFOfor Readonly
fd=open(myfifo,O_RDONLY);
// Read from
FIFOread(fd,arr1,sizeof(ar
r1));
[Link] 28
close(fd);
}
return0;
}
Output:
[Link] 29
OBJECTIVE
c) WriteaCprogramtoillustratetheMessage Queue IPCmechanism
PROGRAM:
//CProgramforMessageQueue(WriterProcess)
#include <stdio.h>
#include <sys/ipc.h>
#include<sys/msg.h>
//structureformessagequeue
struct mesg_buffer {
long
mesg_type;charmesg
_text[100];
} message;
int main()
{
key_tkey;
intmsgid;
//ftoktogenerateuniquekey
key = ftok("progfile", 65);
//msggetcreatesamessage queue
//andreturnsidentifier
msgid=msgget(key,0666|IPC_CREAT);
message.mesg_type = 1;
[Link] 30
printf("Write Data : ");
gets(message.mesg_text);
//msgsndtosendmessage
msgsnd(msgid,&message,sizeof(message),0);
//displaythemessage
printf("Datasend is:%s\n",message.mesg_text);
return0;
}
//CProgramforMessageQueue(ReaderProcess) #include
<stdio.h>
#include <sys/ipc.h>
#include<sys/msg.h>
//structureformessagequeue
struct mesg_buffer {
long
mesg_type;charmesg
_text[100];
} message;
int main()
{
key_tkey;
intmsgid;
//ftoktogenerateuniquekey
key = ftok("progfile", 65);
//msggetcreatesamessage queue
//andreturnsidentifier
msgid=msgget(key,0666|IPC_CREAT);
//msgrcvtoreceivemessage
msgrcv(msgid,&message,sizeof(message),1,0);
[Link] 31
return0;
}
Output:
OBJECTIVE
d) Writea CprogramtoillustratetheSharedMemoryIPCmechanism
PROGRAM:
#include <iostream>
#include <sys/ipc.h>
#include<sys/shm.h>
#include <stdio.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_tkey=ftok("shmfile",65);
//shmgetreturnsanidentifierinshmid
intshmid=shmget(key,1024,0666|IPC_CREAT);
//shmattoattachtosharedmemory
char *str=(char*)shmat(shmid,(void*)0,0);
cout<<"WriteData:";
gets(str);
printf("Datawritteninmemory:%s\n",str);
//detachfromsharedmemory
shmdt(str);
return0;
}
[Link] 32
SHAREDMEMORY FORREADER 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_tkey=ftok("shmfile",65);
//shmgetreturnsanidentifierinshmid
intshmid=shmget(key,1024,0666|IPC_CREAT);
//shmattoattachtosharedmemory
char*str=(char*)shmat(shmid,(void*)0,0);
//detachfromsharedmemory
shmdt(str);
return0;
}
Output:
[Link] 33
EXPERIMENT-6
OBJECTIVE
WriteaCprogramto simulatepagingtechniqueofmemorymanagement.
DESCRIPTION
In computer operating systems, paging is one of the memory management schemes bywhich a
computer stores and retrieves data from the secondarystorage for use in main memory. In the
paging memory-management scheme,theoperatingsystemretrievesdatafromsecondarystoragein
same-size blocks called pages. Paging is a memory-management scheme that permits the physical
address space a process to be noncontiguous. The basic method for implementing paging involves
breaking physical memory into fixed-sized blocks called frames and breaking logical memory into
blocksofthesamesizecalledpages. Whenaprocess isto beexecuted, itspagesare loadedinto any
available memory frames from their source.
AIM:Tosimulatepagingtechniqueofmemorymanagement.
PROGRAM
#include<stdio.h>
#include<conio.h>
main()
{
printf("\[Link][%d]--",i);scanf("%d",&s[i]);
if(s[i]>rempages)
{
[Link] 34
printf("\nMemoryisFull"); break;
}
rempages = rempages - s[i]; printf("\
nEnterpagetableforp[%d]-,i);
for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}
printf("\nEnterLogicalAddresstofindPhysicalAddress"); printf("\
nEnter process no. and pagenumber and offset "); scanf("%d %d
%d",&x,&y, &offset);
if(x>np|| y>=s[i]||offset>=ps)
printf("\nInvalidProcessorPageNumberoroffset"); else
pa=fno[x][y]*ps+offset;
printf("\nThePhysicalAddress is --%d",pa);
getch();
}
INPUT
Enterthememorysize–1000 Enter
the page size --100
[Link] inmemoryare --10 Enter
number of processes --3
Enter [Link][1]-- 4
Enterpagetableforp[1]--- 8 6 9 5
Enter [Link] requiredforp[2]-- 5
Enterpagetableforp[2]--- 1 4 5 7 3
Enter [Link][3]-- 5
OUTPUT
MemoryisFull
EnterLogicalAddresstofindPhysical Address
Enterprocessno. andpagenumberandoffset--2 3 60
ThePhysicalAddressis---------760
[Link] 35
b) OBJECTIVE:Toimplementthememorymanagementpolicy-segmentation
PROGRAM LOGIC:
1. Starttheprogram.
2. Getthenumberofsegments.
3. Getthebaseaddressandlengthforeachsegment.
4. Getthelogicaladdress.
5. Checkwhetherthesegmentnumberiswithinthelimit,ifnotdisplaytheerrormessage.
6. Checkwhetherthebytereferenceiswithinthelimit,ifnotdisplaytheerrormessage.
7. Calculatethephysicalmemoryand display it.
8. Stoptheprogram
SOURCE CODE:
#include<stdio.h>#i
nclude
<conio.h>#include
<math.h>int sost;
voidgstinfo();
void ptladdr();
struct segtab
{ int sno;
int baddr;
int limit;int
val[10];
}st[10];
voidgstinfo()
{inti,j;
printf("\n\tEnterthesizeofthesegmenttable:"); scanf("%d",&sost);
for(i=1;i<=sost;i++)
{
printf("\n\tEntertheinformationaboutsegment:%d",i);
st[i].sno = i;
printf("\n\tEnterthebaseAddress:");
scanf("%d",&st[i].baddr); printf("\n\
tEnter the Limit: ");
scanf("%d",&st[i].limit);
for(j=0;j<=sost;i++)
printf("\t\t%d\t\t%d\t\t%d\n\n",st[i].sno,st[i].baddr,st[i].limit);
printf("\n\nEnter the logical Address: ");
scanf("%d",&swd);
n=swd;
while(n!=0)
{
n=n/10;d++;
[Link] 36
}
s=swd/pow(10,d-1);
disp=swd%(int)pow(10,d-1);
if(s<=sost)
{
if(disp<st[s].limit)
{
paddr = st[s].baddr + disp; printf("\n\t\
tLogicalAddressis:%d",swd);
printf("\n\t\tMappedPhysicaladdressis:%d",paddr); printf("\n\tThe
value is: %d",( st[s].val[disp] ) );
}
Else
printf("\n\t\tLimit ofsegment %dis high\n\n",s);
}
else
printf("\n\t\tInvalidSegmentAddress\n");
}
voidmain()
{charch;
clrscr();
gstinfo();
do
{
ptladdr();
printf("\n\tDoUwanttoContinue(Y/N)");
flushall();
scanf("%c",&ch);
}while(ch== 'Y'||ch=='y');
getch();
}
INPUTANDOUTPUT:
Enter the size of the segment table: 3
Enterthe information about segment: 1
Enter the base Address: 4
EntertheLimit: 5
Enterthe4 addressValue: 11
Enterthe5 addressValue: 12
Enterthe6 addressValue: 13
Enterthe7 addressValue: 14
Enterthe8 addressValue: 15
Entertheinformationaboutsegment:2
Enter the base Address: 5
EntertheLimit: 4
Enterthe5 addressValue: 21
Enterthe6 addressValue: 31
Enterthe7 addressValue: 41
[Link] 37
Enterthe8 addressValue: 51
Entertheinformationaboutsegment:3
Enter the base Address: 3
EntertheLimit: 4
Enterthe3 addressValue: 31
Enterthe4addressValue: 41
Enterthe5 addressValue: 41
Enterthe6 addressValue: 51
[Link]
145
254
334
EnterthelogicalAddress:3
Logical Address is: 3
MappedPhysicaladdressis:3 The
value is: 31
DoUwant toContinue(Y/N)
[Link]
145
254
334
EnterthelogicalAddress:1
Logical Address is: 1
MappedPhysicaladdress is:4
Thevalueis:11DoUwanttoContinue(Y/N)
[Link] 38