Operating System Lab
Operating System Lab
LABORATORYMANUALOPERATIN
G SYSTEM
(BCS-451)
B.TECH – II YEAR
(EVEN SEM 2024-
2025)
Name
RollNo.
Section-Batch
DEPARTMENTOFCOMPUTERSCIENCE&ENGINEERING
ApprovedbyAICTE-AccreditedbyNAAC–‘A’
GradeNH#24,AdhyatmikNagar,Ghaziabad,UP,India
www.imsec.ac.in
VisionandMissionoftheInstituteandDepartment
VisionoftheInstitute
Missionof theInstitute
Mission2:Toinculcatevaluesandethicsamongthelearners.
Mission3:Topromoteindustryinteractionsandproduceyoungentrepreneurs.
Mission4:Tocreateaconducivelearningandresearchenvironmentforlife-longlearningtodevelop the
students as technology leaders and entrepreneurs for addressing societal needs.
VisionoftheDepartment
Missionof theDepartment
Mission1:Toprovidequalityeducationinboththetheoreticalandappliedfoundationsof Computer
Science&Engineering.
Mission2:ConductresearchinComputerScience&Engineeringresultingininnovationsthereby
nurturing entrepreneurial thinking.
Mission3:To inculcateteam buildingskills andpromotelife-long learningwith ahighsocietal and
ethical values.
2
DEPARTMENTOFCOMPUTERSCIENCE&ENGINEERING
CSEDepartmentProgramEducationalObjectives(PEOs)
CSEDepartment ProgramSpecificOutcomes(PSOs)
B.TechComputerScience&EngineeringDepartmenthasthefollowingProgramSpecificOutcomes:
PSO1:Toanalyzeanddemonstrate,therecentengineeringpractices,ethicalvaluesandstrategies in real
time world problems to meet the challenges for the future.
PSO2:Todevelopadaptivecomputingsystemusingcomputationalintelligencestrategiesand algorithmic
design to address diverse challenges in data analysis and machine learning.
3
ProgramOutcomes(POs)andProgramSpecificOutcomes(PSOs)
S.No. ProgramOutcomes/ProgramSpecificOutcomes
Engineeringknowledge:Applytheknowledgeofmathematics,science,engineering
PO1. fundamentals,andanengineeringspecializationtothesolutionofcomplex
engineeringproblems.
Problemanalysis: Identify,formulate,reviewresearchliterature,andanalyze
PO2. complex engineeringproblems reachingsubstantiatedconclusions usingfirst
principlesof mathematics, natural sciences, and engineering sciences.
Design/development of solutions:Design solutions for complex engineering
problems anddesignsystemcomponents or processesthatmeetthespecifiedneedswith
PO3.
appropriate consideration for the public health and safety, and
thecultural,societal, andenvironmentalconsiderations.
Conduct investigations of complex problems: Use research-based
PO4. knowledgeand researchmethodsincludingdesignofexperiments,analysisand
interpretationofdata, and synthesis ofthe information to provide valid conclusions.
Moderntoolusage:Create,select,andapplyappropriatetechniques, resources, and
modernengineeringandIT toolsincludingpredictionand
PO5.
modellingtocomplexengineeringactivitieswithanunderstandingofthe
limitations.
The engineer and society:apply reasoning informed by the contextual knowledge
PO6. toassesssocietal,health,safety,legalandculturalissuesandtheconsequent
responsibilitiesrelevanttotheprofessionalengineeringpractice.
Environmentandsustainability: Understandtheimpactoftheprofessional
PO7. engineeringsolutionsinsocietalandenvironmentalcontexts,anddemonstratethe
knowledgeof,andneed forsustainabledevelopment.
Ethics: Applyethicalprinciples and commit toprofessionalethicsand
PO8.
responsibilities and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member
PO9.
or leader in diverse teams, and in multidisciplinary settings.
Communication:Communicateeffectively oncomplex engineeringactivitieswith
theengineeringcommunityandwithsocietyatlarge,suchas,beingableto
PO10.
comprehendand write effective reports and design documentation, make effective
presentations,and give and receive clear instructions.
Project management and finance:Demonstrate knowledge and understanding of
the engineering and management principles and applythese to one’s own work, as a
PO11.
memberandleaderinateam,tomanageprojectsandinmultidisciplinary
environments.
Life-longlearning:Recognizetheneedfor,andhavethepreparationandability to engage
PO12. in independent and life-long learning in the broadest context of technological change.
Toanalyzeanddemonstrate,therecentengineeringpractice,ethicalvaluesand strategies in
PSO1. real time world problems to meet the challenges for the future.
To Develop adaptive computing system using computational intelligence strategies
and algorithmic design to address diverse challenges in data analysis and
PSO2.
machinelearning
4
GENERALLABORATORYINSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time),those who come after5minuteswillnotbeallowedinto the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis /program/experiment details.
3.Studentshouldenterintothelaboratorywith:
Laboratoryobservationnoteswithallthedetails(Problemstatement,Aim,Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
ProperDresscodeandIdentitycard.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
9. Studentsmusttakethepermissionofthefacultyincaseofanyurgencytogoout;ifanybody found
loiteringoutsidethe lab/classwithout permissionduring working hourswillbetreated seriously
and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer systembefore he/she leaves the
labafter completing thetask (experiment) inallaspects.He/she must ensure the system/ seat is
kept properly.
5
DETAILSOFTHEEXPERIMENTSCONDUCTED
(TOBEUSEDBYTHESTUDENTSINTHEIRRECORDS)
INDEX
DATE
S.No TITLEOFTHEEXPERIMENT OFSUBMISSI FACULTYS
ON IGNATURE
1
10
11
12
6
7
STUDYANDEVALUATIONSCHEME
Course Course
TeachingScheme CreditsAssigned
Code Name
Operating Theory Practical Tutorial Theory Practical Tutorial Total
BCS-
Systems 03 02 00 03 01 -- 04
401(T)BCS-
(70 (50
451(P)
Marks) Marks)
8
IMSEngineeringCollege
NH-09,AdhyatmikNagar,NearDasna, Distt. Ghaziabad,U.P.
Tel:(0120)4940000
DepartmentofComputerScienceandEngineering
Bloom’sLevel
COURSEOUTCOMES
AnalyzeandsimulateCPUschedulingalgorithmforprocessscheduling. K4
C216.2
C216.3 Implementmemorymanagementtechniques. K3
Analyze&Simulatedeadlockmanagementtechniques
K2,K3
C216.4
Implementtheprocesssynchronizationproblemusingsemaphore.
K3
C216.5
CO-POMatrix
CourseO
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
utcome
C216.1 3 3 3 3 2 2 1 1 1 1 1 3 2 2
C216.2 3 3 3 3 2 2 1 1 1 1 1 3 2 2
C216.3 3 3 3 3 2 2 1 1 1 1 1 3 2 2
C216.4 3 3 2 3 2 2 1 1 1 1 2 3 2 2
C216.5 3 3 3 3 2 2 1 1 1 1 2 3 2 2
C216 3.0 3.0 2.8 3.0 2.0 2.0 1.0 1.0 1.0 1.0 1.4 3.0 2.0 2.0
9
LISTOFPROGRAMS
Subject:OperatingSystemLab Code:BCS-451
9 ImplementationofBanker’salgorithm. C216.4
10
10 Conversionofresourceallocationgraph(RAG)towait forgraph (WFG) C216.4
for each type of method used for storing graph.
11 Implement the solution for Bounded Buffer (producer-consumer) C216.5
problemusinginterprocesscommunicationtechniques-Semaphores.
12 ImplementthesolutionsforReaders-Writer’sproblemusinginter process C216.5
communication technique –Semaphore.
11
EXPERIMENTNO.-1
AIM:Studyofhardwareandsoftwarerequirementsofdifferent
operatingsystems(UNIX,LINUX,WINDOWSXP,WINDOWS7/8).
Procedure:
varioussoftwareandhardwarerequirementsfordifferentOperatingSystem areasfollow:
1) MSDOS
• ATcompatible CPUwith386orgreaterprocessor
• 16MBofRAM
• 1.44Mbfloppydiskettedrive orCD-ROMdrive
• EGA640x480orbetterscreenresolution
• BootableFloppy or CD-ROM diskcontaining DOS, or startup diskfor
Windows 95/98.
• SourceHDD/SSDoftypeIDE/SATA/SCSIattached
• DestinationFAT/FAT32volumethatmaybelocal ormappednetwork drive
for storing images
2) LINUX
Processor 64-bit,EM64T
RAM 1GBorgreater
Swapspace 1GBorgreater
Diskspace 500MBfreespace
3) UNIX
• RandomAccessMemory(RAM)
• 256MBrecommended
• 128MBminimum
• 250MBavailableharddrivespace(seenote)
• CD-ROMdrive
• TCP/IPnetworkinterface
4) Windows98
• 486DX66MHzorbetterprocessor(Pentiumrecommended)
• 16megabytes(MB)ofmemory(24 MBrecommended)
• 120 MB minimum of free hard-disk space (Note that typical installation
requires approximately 195 MB of free hard-disk space, but may range
between 120 MB to 295 MB, depending
• CD-ROMorDVD-ROMdrive
12
• 3.5-inchhigh-densityfloppydiskdrive
• Displayadapter andmonitorthatsupportVGAorhigherresolution
• MicrosoftMouseorcompatiblepointingdevice.
5) WindowsXP
• Pentium233-megahertz(MHz)processoror
faster(300MHzisrecommended)
• Atleast64megabytes(MB)ofRAM(128MBisrecommended)
• Atleast1.5gigabytes(GB)ofavailablespaceontheharddisk
• CD-ROMorDVD-ROMdrive
• VideoadapterandmonitorwithSuperVGA(800x600)orhigherresolution
6) Windows2000
• 133MHzorhigherPentium-compatibleCPU
• 64MBRAMrecommendedminimum(4GBRAMmaximum)
• 2GBharddiskwitha minimumof650MBoffree space.Additionalfree
hard disk space is required if you are installing over a network.
• PentiumII orbetter
• Atleast128MBofRAM
• 4GBharddrive,withatleast1GBfree
7) Windows8
• CPUSPEED: 1 GHzorfasterprocessor
• RAM: 1 GBRAM(32-bit)or2GBRAM(64-bit)
• VIDEOCARD: DirectX9 graphicswithWDDM1.0driver
• PIXELSHADER: 2.0
• FREEDISKSPACE: 16GBspace(32-bit)or20 GB(64-bit)
8) Windows10
• Processor:1gigahertz(GHz)orfasterprocessor
• RAM:1gigabyte (GB)for32-bitor 2GBfor64-bit
• Harddiskspace:16 GBfor 32-bitOSor20GBfor 64-bitOS
• Graphicscard:DirectX 9orlaterwithWDDM1.0driver
• Display:800x600
13
EXPERIMENTNO.-2
AIM:ExecutevariousUNIXsystemcallsfor
i. Processmanagement
ii. Filemanagement
iii. Input/outputSystemscalls
Procedure:
BasiccommandsusedforprocessmanagementandfilemanagementinLinux/Unixare as
follow:
ProcessManagement:
1)top:
The top(table ofprocesses) command shows a real-time view ofrunning processes in
Linux and displays kernel-managed tasks. The command also provides a system
information summary that shows resource utilization, including CPU and
memoryusage.
2)ps:
The ps (processes status) command is a native Unix/Linux utility for viewing
information concerning a selection of running processes on a system: it reads this
information from the virtual files in the /proc filesystem.
3)sleep:
The sleep command suspends the calling process ofthe next command for a specified
amount of time. This property is useful when the following command's execution
depends on the successful completion of a previous command.
4)jobs:
Jobscommandisusedtolistthejobsthatyouarerunninginthebackgroundandinthe
foreground.Ifthepromptisreturnedwithnoinformationnojobsarepresent.Allshells are
not capable of running this command.
5)kill:
The command killsends the specified signalto the specified processes. Ifno signal is
specified,theTERMsignalissent.Thedefaultactionforthissignalistoterminatetheprocess
.
FileManagement:
1)ls:
Thelscommandisusedtolistfiles."ls"onitsownlistsallfilesinthecurrentdirectory except
for hidden files.
14
2)ls-s:
Thels-swilllistallfilessizes.
3)ls-a:
Thels-awilllistallfilesincludinghiddenfiles(fileswithnamesbeginningwithadot).
4)mkdir:
The mkdir command in Linux/Unix allows users to create or make new directories.
mkdir stands for “make directory.” With mkdir , you can also set permissions, create
multiple directories (folders) at once.
5)vi:
Thevicommandisaninteractivetexteditorthatisdisplay-oriented:thescreenofyour
terminal acts as a window into the file you are editing. Changes you make to the file
are reflected in what you see. Using vi you can insert text anywhere in the file very
easily. Most of the vi commands move the cursor around in the file.
6)cat:
The cat command is a utility command in Linux. One of its most commonly known
usages isto print the content ofa file ontothe standardoutput stream. Other thanthat,
the cat command also allows us to write some texts into a file.
7)mv:
Themvcommandmovesfilesanddirectoriesfromonedirectorytoanotherorrenames
afileordirectory.Ifyoumoveafileordirectorytoanewdirectory,itretainsthebase
filename.Whenyoumoveafile,alllinkstootherfilesremainintact,exceptwhenyou move
it to a different file system.
8)cv:
The cp command to create a copy of the contents of the file or directory specified by
the Source File or Source Directory parameters into the file or directory specified by
the Target File or Target Directory parameters.
9)rm:
The rm stands for remove here. rm command is used to remove objects such as files,
directories, symbolic links and so on from the file system like UNIX. To be more
precise, rm removes references to objects from the filesystem, where those objects
might have had multiple references(for example, a file withtwo different names). By
default, it does not remove directories.
10) rmdir:
Thermdircommandremovesthedirectory,specifiedbytheDirectoryparameter,from
thesystem.Thedirectorymust beemptybeforeyoucanremoveit,andyoumust have
writtenpermissioninitsparentdirectory.Usethels-alcommandtocheckwhetherthe
directory is empty.
15
SystemCalls:
Command&Output:
ProcessManagement
:
16
FileManagement:
17
18
EXPERIMENTNO.-3
AIM:ImplementCPUSchedulingPolicies:
i. FCFS
ii. SJF
iii. Priority
i. FirstComeFirstServe(FCFS)
Procedure:
To calculate the average waiting time using the FCFS algorithm first the waiting
time ofthe first process is kept zero and the waiting time ofthe second process is
the burst time of the first process and the waiting time of the third process is
thesumofthebursttimesofthefirst
andthesecondprocessandsoon.Aftercalculatingallthewaitingtimestheaveragewaitin
gtime iscalculatedastheaverageofallthe waiting times. FCFS mainly says first
come first serve the algorithm which came first will be served first.
ALGORITHM:
Step1:Starttheprocess
Step2: Acceptthe number ofprocessesinthereadyQueue
Step3:ForeachprocessinthereadyQ,assigntheprocessnameandthebursttime
Step4:Setthewaitingofthefirst processas‗0‘anditsbursttime asitsturnaround time
Step 5: for each process in the Ready Q calculate
a).Waiting time (n) = waiting time (n-1) + Burst time (n-1) b). Turnaround time
(n)= waiting time(n)+Burst time(n)
Step6:Calculate
a) Averagewaitingtime=TotalwaitingTime /Numberofprocess
Code/Method:
#include<stdio.h>#include<conio.h>m
ain()
{
intbt[20],wt[20],tat[20],i,n;floatwtavg,tatavg;clrs
cr();
printf("\nEnter the number of processes --
");scanf("%d",&n);
19
for(i=0;i<n;i++)
{
printf("\nEnterBurst TimeforProcess%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("\tPROCESS\tBURSTTIME\tWAITINGTIME\tTURNAROUNDTIME\
n");
for(i=0;i<n;i++)
printf("\n\tP%d \t\t %d \t\t %d \t\t %d",i,bt[i], wt[i], tat[i]); printf("\
nAverageWaiting Time -- %f", wtavg/n);
printf("\nAverageTurnaround Time--%f",tatavg/n);getch();
}
Input:
Enterthenumberofprocesses-- 3
EnterBurstTimeforProcess0-- 24
EnterBurstTimeforProcess1-- 3
EnterBurstTimeforProcess2-- 3
Output:
20
ii. SHORTESTJOBFIRST
Procedure:
To calculate the average waiting time in the shortest job first algorithmthe sorting of
theprocessbasedontheirbursttimeinascendingorderthencalculatethewaitingtime
ofeachprocessasthesumofthe bursting timesofalltheprocesspreviousorbeforeto that
process.
ALGORITHM:
Step1:Starttheprocess
Step2: Acceptthe numberofprocessesinthereadyQueue
Step3:Foreachprocess inthereadyQ,assigntheprocessidandaccept the
CPU burst time
Step4:StarttheReadyQaccordingtheshortestBursttimebysorting according
to lowest to highest burst time.
Step5: Setthewaitingtimeofthefirstprocess as‗0‘andits turnaround time as
its burst time.
Step6:Sorttheprocessesnamesbasedontheir BurttimeStep7:Foreach
processthe ready queue, calculate
Waitingtime(n)=waitingtime(n-1)+Bursttime(n-1)
Turnaround time (n)= waiting time(n)+Burst time(n)
Step 8: Calculate
Average waiting time = Total waiting Time / Number of
processAverageTurnaroundtime=TotalTurnaroundTime/Numberofproc
ess Step 9: Stop the process
Code/Method:
#include<stdio.h>#include<conio.h>main
()
{
intp[20],bt[20],wt[20],tat[20],i,k,n,temp;floatwtavg,tatavg;clrscr(
);
printf("\
nEnterthenumberofprocesses--");scanf("%d",&n);for(i=0;i<n;i+
+)
{
p[i]=i;
printf("EnterBurstTimeforProcess%d--",i);scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)for(k=i+1;k<n;k++)if(bt[i]>bt[k])
{
21
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\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\tP%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("\nAverageTurnaroundTime--%f", tatavg/n);getch();}
Input:
Enterthenumberofprocesses--4
EnterBurstTimeforProcess0-- 6
EnterBurstTimeforProcess1-- 8
EnterBurstTimeforProcess2-- 7
EnterBurstTimeforProcess3-- 3
Output:
22
iii. PRIORIT
DESCRIPTION:
ALGORITHM:
Step1:Starttheprocess
Step2: Acceptthe number ofprocessesinthereadyQueue
Step3:Foreachprocess inthereadyQ,assigntheprocessidandaccept theCPU burst
time
Step4:Sortthereadyqueue accordingtotheprioritynumber.
Step5:Setthewaitingofthefirstprocessas‗0‘anditsbursttimeasits turnaround time
Step 6: Arrange the processes based on process priority
Step7:ForeachprocessintheReadyQ calculate Step8:
foreachprocessintheReadyQcalculate
a) Waitingtime(n)=waitingtime(n-1)+Bursttime(n-1)
b) Turnaroundtime(n)=waitingtime(n)+Bursttime(n)
Step9:Calculate
c) Averagewaitingtime=TotalwaitingTime / Numberofprocess
d) AverageTurnaroundtime=TotalTurnaroundTime/NumberofprocessPrint the
results in an order.
Step10:Stop
SOURCECODE:
#include<stdio.h>main()
{
intp[20],bt[20],pri[20],wt[20],tat[20],i,k,n,temp;floatwtavg,tatavg;clrscr(
);
printf("Enterthenumberofprocesses---");scanf("%d",&n); for(i=0;i<n;i+
+){ p[i] = i;
printf("EntertheBurstTime&PriorityofProcess %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]; 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++)
23
{
24
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\tBURSTTIME\tWAITINGTIME\
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
TurnaroundTimeis---%f",tatavg/n);getch();}
INPUT
Enterthe numberofprocesses--5
EntertheBurstTime&PriorityofProcess0---103
EntertheBurstTime&PriorityofProcess1---1
1
EntertheBurstTime&PriorityofProcess2---2 4
EntertheBurstTime&PriorityofProcess3---1 5
EntertheBurstTime&PriorityofProcess4---5OUTPUT 2
PROCESSPRIORITY BURST TIMEWAITING
TIME TIMETURNAROUND
1 1 1 0
1
4 2 5 1 6
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is ---
8.200000AverageTurnaroundTimeis
12.000000
25
EXPERIMENTNO.-4
AIM:Implementfilestorageallocationtechnique:
i. Contiguous(using array)
ii. Linked–list(usinglinked-list)
iii. Indirectallocation(indexing)
i) SEQUENTIAL:
Procedure:
Themostcommonformoffilestructureisthesequentialfileinthistypeoffile,afixed format
isusedforrecords.Allrecords(ofthesystem)havethesame length,consisting of the same
number of fixed length fields in a particular order because the length and position of
each field are known, onlythe values of fields need to bestored, the field name and
length for each field are attributes of the file structure.
ALGORITHM:
Step1:Starttheprogram.
Step2:Getthe numberoffiles.
Step3:Getthememoryrequirementofeachfile.
Step4:Allocatetherequired locationsto eachinsequentialordera).Randomlyselect a
location from availablelocation s1= random(100);
a) Checkwhethertherequiredlocationsarefreefromtheselectedlocation.
if(b[s1].flag==0){
for (j=s1;j<s1+p[i];j++){if((b[j].flag)==0)count++;
}
if(count==p[i])break;
}
b) Allocate and set flag=1 to the allocated
locations.for(s=s1;s<(s1+p[i]);s++)
{
k[i][j]=s;j=j+1;b[s].bno=s;b[s].flag=1;
}
Step5:Print theresultsfileno,length,Blocksallocated.Step6:Stoptheprogram
Code/Method:
#include<stdio.h>mai
n()
{
26
intf[50],i,st,j,len,c,k;clrscr();for(i=0;i<50;i++)f[i]=0;
printf("\n Enter the starting block&length of
file");scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++)if(f[j]==0)
{
f[j]=1
;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Blockalreadyallocated");break;
}
if(j==(st+len))
printf("\nthefileisallocatedtodisk");
printf("\nifuwanttoentermorefiles?(y-1/n-0)");scanf("%d",&c);
if(c==1) goto X; else exit();
getch();
}
OUTPUT:
Enterthestartingblock&lengthoffile4104->15->1
6->1
7->1
8->1
9->1
10->1
11->1
12->1
13->1
Thefileisallocatedtodisk.
ii) INDEXED:
Procedure:
Inthechainedmethodfileallocationtablecontainsafieldwhichpointstostartingblock of
memory. From it for each bloc a pointer is kept to next successive block. Hence,
there is no external fragmentation.
ALGORITHM:
Step1:Starttheprogram.
Step2:Getthenumberoffiles.
27
Step3:Getthememoryrequirementofeachfile.
Step4:Allocatetherequiredlocationsbyselectingalocationrandomlyq=random(100);
a) Checkwhethertheselectedlocationisfree.
b) Ifthelocationisfreeallocateandsetflag=1totheallocatedlocations.
q=random(100);
{
if(b[q].flag==0)
b[q].flag=1;
b[q].fno=j;
r[i][j]=q;
Step5:Printtheresultsfileno,length,Blocksallocated. Step
6: Stop the program
Code/Method:
#include<stdio.h>Intf[50],i,k,j,inde[
50],n,c,count=0,p;main()
{
clrscr(); for(i=0;i<50;i+
+)f[i]=0;
x:printf("enterindexblock\
t");scanf("%d",&p);
if(f[p]==0)
{f[p]=1;
printf("enternooffilesonindex\
t");scanf("%d",&n);
}
else
{
printf("Block already allocated\
n");goto x;
}
for(i=0;i<n;i+
+)scanf("%d",&inde[i]
);for(i=0;i<n;i++)
if(f[inde[i]]==1)
{
printf("Block
alreadyallocated");goto x;
}
for(j=0;j<n;j++)f[inde[j]]=1;
28
printf("\n
allocated");printf("\
nfileindexed");
for(k=0;k<n;k++)
printf("\n %d->%d:%d",p,inde[k],f[inde[k]]);
printf("Enter1toentermorefilesand0toexit\
t");scanf("%d",&c);
if(c==1)gotox;
else
exit();getch();
}
OUTPUT:enterindexblock9Enternooffilesonindex3123 Allocated
File indexed 9->1:1
9->2;1
9->3:1enter1to entermorefilesand0 toexit
iii) LINKED:
Procedure:
Inthechainedmethodfileallocationtablecontainsafieldwhichpointstostartingblock of
memory. From it for each bloc a pointer is kept to next successive block. Hence,
there is no external fragmentation
ALGORTHIM:
Step1:Starttheprogram.Step2:Getthenumberoffiles. Step
3: Get the memory requirement of each file.
Step4:Allocatetherequiredlocationsbyselectingalocationrandomlyq=random(100);
a) Checkwhethertheselectedlocationisfree.
b) Ifthelocationisfreeallocateandsetflag=1totheallocatedlocations.
While allocating next location address to attach it to previous location
for(i=0;i<n;i++)
{
for(j=0;j<s[i];j++)
{
q=random(100); if(b[q].flag==0)
b[q].flag=1; b[q].fno=j;
r[i]
[j]=q;if(j>
0)
{
}
}
p=r[i][j-1];b[p].next=q;}
29
Step5:Printtheresultsfileno,length,Blocksallocated. Step
6: Stop the program
Code/Method:
#include<stdio.h>mai
n()
{
int f[50],p,i,j,k,a,st,len,n,c;
clrscr();
for(i=0;i<50;i+
+)f[i]=0;
printf("Enterhowmanyblocksthatarealreadyallocated");scanf("%d",
&p);
printf("\
nEntertheblocksno.sthatarealreadyallocated");for(i=0;i<p;i++)
{
scanf("%d",&a
); f[a]=1;
}
X:
printf("Enter the
startingindexblock&length");scanf("%d
%d",&st,&len);
k=len;for(j=st;j<(k+st)
;j++)
{
if(f[j]==0)
{f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n%d-
>fileisalreadyallocated",j);k++;
}
}
printf("\nIfuwanttoenteronemorefile?(yes-1/no-0)");
scanf("%d",&c); if(c==1)
goto
X;elseexi
t();getch(
);}
30
OUTPUT:
31
Enterhowmanyblocksthatarealreadyallocated3Entertheblocksno.sthatare already
allocated 4 7 Enter the starting index block&length 3 7 9
3->1
4->1fileisalreadyallocated 5->1
6->1
7->1 file is alreadyallocated 8->1
9->1fileisalreadyallocated10-
>111->1
12->1
VivaQuestions:
1. ListVariousTypesofFiles.
2. Whatarevariousfileallocationstrategies?
3. Whatislinkedallocation?
4. What areadvantagesofLinkedallocation?
5. Whataredisadvantagesofsequentialallocation?
32
EXPERIMENTNO.-5
AIM:Implementationofcontiguousallocationtechniques:
i. Worst-Fit
ii. Best-Fit
iii. First-Fit
Procedure:
One of the simplest methods for memory allocation is to divide memory into several fixed-
sizedpartitions.Eachpartitionmaycontainexactlyoneprocess.Inthismultiple-
partitionmethod,whenapartitionisfree,aprocessisselectedfromtheinputqueueand is
loaded into the free partition. When the process terminates, the partition becomes
availableforanotherprocess.Theoperatingsystemkeepsatableindicatingwhichparts of
memory are available and which are occupied. Finally, when a process arrives and
needsmemory,a memorysectionlargeenoughforthisprocessisprovided.Whenit is time
to load or swap a process into main memory, and if there is more than one free block
of memoryof sufficient size, then the operating system must decide which free
blocktoallocate.Best-fitstrategychoosestheblockthatisclosestinsizetotherequest. First-
fit chooses the first available block that is large enough. Worst-fit chooses the largest
available block.
i) WORST-FIT
Code/Method:
#include<stdio.h>#includ
e<conio.h>#defin
e max 25 void
main()
{
intfrag[max],b[max],f[max],i,j,nb,nf,temp;staticintbf[max],ff[max];clrscr();
printf("\n\tMemory ManagementScheme - First
Fit");printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enterthenumberoffiles:");scanf("%d",&nf)
;
printf("\nEnterthe size of the blocks:-\
n"); for(i=1;i<=nb;i++)
{
printf("Block%d:",i);
scanf("%d",&b[i]);
}
33
printf("Enter the size of the files :-\n");for(i=1;i<=nf;i++)
{
printf("File%d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];if(temp>=0)
{
ff[i]=j;break;
}
}
}
frag[i]=temp;bf[ff[i]]=1;
}
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\
tFragement");for(i=1;i<=nf;i++)printf("\n%d\t\t%d\t\t%d\t\t
%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);getch();
INPUT
Enterthesizeofthefiles:-File1:1 File
2: 4
OUTPUT
FileNo FileSize BlockNo BlockSize Fragment
1 1 1 5 4
2 4 3 7 3
ii) BEST-FIT
34
#include<stdio.h>#include<conio.h>#defi
ne max 25
voidmain()
{
intfrag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;staticintbf[max],ff[max];cl
rscr();
printf("\
nEnterthenumberofblocks:");scanf("%d",
&nb);
printf("Enterthenumberoffiles:");scanf("%
d",&nf);
printf("\nEnterthesizeoftheblocks:-\
n");for(i=1;i<=nb;i++)
printf("Block%d:",i);
scanf("%d",&b[i]);
printf("Enter the size of the files :-\
n"); for(i=1;i<=nf;i++)
{
printf("File%d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];if(temp>=0)
if(lowest>temp)
{
ff[i]=j;lowest=temp;
}
}}
frag[i]=lowest;bf[ff[i]]=1;lowest=10000;
}
printf("\nFileNo\tFile Size \tBlockNo\tBlock Size\
tFragment");for(i=1;i<=nf&&ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);getch();
}
INPUT
Enterthenumberofblocks:3
Enterthe numberoffiles:2
35
Enterthesizeofthe blocks:-Block 1:5
36
Block2:2
Block3:7
Enterthe sizeofthe files:-File1:1
File2:4
OUTPUT
File No File Size
BlockNoBlock Size
Fragment
1 1 2 2 1
2 4 1 5 1
iii) FIRST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
intfrag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;staticintbf[max],ff[max];clrscr(
);
printf("\n\tMemoryManagementScheme-WorstFit");
printf("\nEnter the number of
blocks:");scanf("%d",&nb);
printf("Enterthenumberoffiles:");scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\
n");for(i=1;i<=nb;i++)
{
printf("Block%d:",i);
scanf("%d",&b[i]);
}
printf("Enterthesizeofthefiles:-\n");for(i=1;i<=nf;i++)
{
printf("File%d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)//ifbf[j]isnotallocated
{
temp=b[j]-f[i];if(temp>=0)
37
if(highest<temp)
{
}
}
frag[i]=highest;bf[ff[i]]=1;highest=0;
}
ff[i]=j;highest=temp;
}
printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\
tFragement");for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);getch();
}
INPUT
Enterthenumberofblocks:3Enterthe number of
files: 2
Enterthesize oftheblocks:-
Block1:5
Block2:2
Block3:7
Enterthesizeofthefiles:-
OUTPUT
VivaQuestions
1) Whatisvirtualmemory?
2) Definecontextswitching.
3) Whatis fragmentation?Differenttypesoffragmentation.
4) ExplainDemandpaging.
5) Explainbest fit andworstfit.
38
EXPERIMENTNO.-6
AIM:Calculationofexternalandinternalfragmentation
i. Freespacelistofblocksfromsystem
ii. Listprocessfilefromthesystem
Procedure:
After implementingeachallocationalgorithm, list
theamountoffreespaceblocksleftoutafterperformingallocation.Whenablockwhichisnot
atallallocatedto anyprocessor file, it adds to external fragmentation. When a file or
process is allocated the free blockandstillsomepartofit
isleftunused,wecountsuchunusedportionintointernalfragmentation.
Code/Method:
#include<stdio.h>#inclu
de<conio.h>main
()
{
int ms,mp[10],i,
temp,n=0;charch='y';cl
rscr();
printf("\
nEnterthetotalmemoryavailable(inBytes)--");scanf("%d",&ms
);
temp=ms;for(i=0;ch=='y';i++,n++)
{
printf("\nEntermemoryrequiredforprocess%d(inBytes)--",i+1);scanf("%d",&mp[i]);
if(mp[i]<=temp)
{
printf("\nMemoryisallocatedforProcess%d",i+1); temp =
temp - mp[i];
}
else
{
printf("\nMemoryisFull");break;
}
printf("\nDoyouwanttocontinue(y/n)--");
scanf("%c",&ch);
}
39
printf("\n\nTotal Memory Available -- %d", ms);
printf("\n\n\tPROCESS\t\
tMEMORYALLOCATED");for(i=0;i<n;i++)
printf("\n\t%d\t\t%d",i+1,mp[i]);
printf("\n\nTotalMemoryAllocatedis%d",ms-temp);
printf("\nTotalExternal Fragmentation is
%d",temp);getch();
}
Output:
Enterthetotalmemoryavailable(inBytes)–1000
Entermemoryrequiredforprocess1(inBytes)–
400 Memory is allocated for Process 1
Doyouwanttocontinue(y/n)--y
Entermemoryrequiredforprocess2(inBytes)--
275 Memory is allocated for Process 2
Doyouwanttocontinue(y/n) –y
Entermemoryrequiredforprocess3(inBytes)–
550 Memory is Full
Total Memory Available – 1000
PROCESSMEMORYALLOCATED
1 400
2 275
Total Memory Allocated is 675
TotalExternalFragmentationis325
Code/Method:
#include<stdio.h
>#include<conio.
h>main()
{
int ms,mp[10],i,
temp,n=0;charch='y';
clrscr();
printf("\nEnterthetotalmemoryavailable(in
Bytes)--");
scanf("%d",&ms);
temp=ms;for(i=0;ch=='
y';i++,n++)
{
printf("\nEntermemoryrequiredforprocess%d(in
Bytes) --",i+1);
40
scanf("%d",&mp[i]);if
(mp[i]<=temp)
{
printf("\nMemoryisallocatedforProcess
%d",i+1);
temp=temp -mp[i];
}
else
{
printf("\nMemoryisFull");break;
}
printf("\nDoyouwanttocontinue(y/n)--");
scanf("%c",&ch);
}
printf("\n\nTotalMemoryAvailable --%d",ms);
printf("\n\n\tPROCESS\t\
tMEMORYALLOCATED");
for(i=0;i<n;i++)
printf("\n\t%d\t\t%d",i+1,mp[i]);
printf("\n\nTotalMemoryAllocatedis%d",ms-
temp);
printf("\nTotalExternalFragmentationis
%d",temp);
getch();
}
Enterthetotalmemoryavailable(inBytes)–1000
Entermemoryrequiredforprocess1(inBytes)–
400 Memory is allocated for Process 1
Doyouwanttocontinue(y/n)--y
Entermemoryrequiredforprocess2(inBytes)--
275 Memory is allocated for Process 2
Doyouwanttocontinue(y/n) –y
Entermemoryrequiredforprocess3(inBytes)–
550 Memory is Full
Total Memory Available – 1000
PROCESSMEMORYALLOCATED
1 400
2 275
Total Memory Allocated is 675
TotalExternalFragmentationis325
41
VivaQuestions
1) Whatisfragmentation?
2) Differentiatebetweeninternalandexternalfragmentation.
3) Externalfragmentationwillnotoccurwhen?
4) Externalfragmentationexistswhen?
5) Howfragmentationworksonoperatingsystem?
42
EXPERIMENTNO.-7
Procedure:
Code/Method:
#include<stdio.h>
#include<conio.h>
voidcreate(int,int);
voiddel(int);
voidcompaction();
voiddisplay();
intfname[10],fsize[10],fstart[10],freest[10],freesize[10],m=0,n=0,start;
intmain()
intname,size,ch,i;
int*ptr;
//clrscr();
ptr=(int*)malloc(sizeof(int)*100);
start=freest[0]=(int)ptr;
43
freesize[0]=500;
44
printf("\n\n");
for(i=0;i<=m;i++)
printf(" %d %d\n",freest[i],freesize[i]);
printf("\n\n");
while(1)
printf("1.Create.\n");
printf("2.Delete.\n");
printf("3.Compaction.\n");
printf("4.Exit.\n");
printf("Enteryourchoice:");
scanf("%d",&ch);
switch(ch)
case1:
printf("\nEnterthenameoffile:");
scanf("%d",&name);
printf("\nEnterthesizeofthefile:");
scanf("%d",&size);
create(name,size);
break;
case2:
printf("\nEnterthefilenamewhichuwanttodelete:");
scanf("%d",&name);
45
del(name);
break;
case3:
compaction();
printf("\nAftercompactionthetableswillbe:\n");
display();
break;
case4:
exit(1);
default:
printf("\nYouhaveentered awrongchoice.\n");
voidcreate(intname,intsize)
inti,flag=1,j,a;
for(i=0;i<=m;i++)
if(freesize[i]>=size)
a=i,flag=0;
if(!flag)
for(j=0;j<n;j++);
n++;
fname[j]=name;
fsize[j]=size;
46
fstart[j]=freest[a];
freest[a]=freest[a]+size;
freesize[a]=freesize[a]-size;
printf("\nThememorymapwillnow be:\n\n");
display();
else
printf("\nNoenoughspaceisavailable.Systemcompaction...........");
flag=1;
compaction();
display();
for(i=0;i<=m;i++)
if(freesize[i]>=size)
a=i,flag=0;
if(!flag)
for(j=0;j<n;j++);
n++;
fname[j]=name;
fsize[j]=size;
fstart[j]=freest[a];
freest[a]+=size;
freesize[a]-=size;
printf("\nThememorymapwillnowbe:\n\n");
display();
47
}
else
printf("\nNoenoughspace.\n");
voiddel(intname)
inti,j,k,flag=1;
for(i=0;i<n;i++)
if(fname[i]==name)
break;
if(i==n)
flag=0;
printf("\nNosuchprocessexists.........\n");
else
m++;
freest[m]=fstart[i];
freesize[m]=fsize[i];
for(k=i;k<n;k++)
fname[k]=fname[k+1];
fsize[k]=fsize[k+1];
fstart[k]=fstart[k+1];
48
}
n--;
if(flag)
display();
voidcompaction()
inti,j,size1=0,f_size=0;
if(fstart[0]!=start)
fstart[0]=start;
for(i=1;i<n;i++)
fstart[i]=fstart[i-1]+fsize[i-1];
else
for(i=1;i<n;i++)
fstart[i]=fstart[i-1]+fsize[i-1];
f_size=freesize[0];
for(j=0;j<=m;j++)
size1+=freesize[j];
49
freest[0]=freest[0]-(size1-f_size);
freesize[0]=size1;
m=0;
voiddisplay()
inti;
printf("\n***MEMORYMAPTABLE*** \n");
for(i=0;i<n;i++)
printf("%d%10d%10d\n",fname[i],fsize[i],fstart[i]);
printf("\n\n");
printf("\n\n***FREE SPACETABLE***\n\n");
for(i=0;i<=m;i++)
printf(" %d %d\n",freest[i],freesize[i]);
Output:
50
VivaQuestions
1) Whatisfragmentation?
2) Discusstheneedofcompaction.
3) Explainthe term“paging”.
4) List variouspagereplacementalgorithms.
5) Explainresourceallocationuseinmemory
51
EXPERIMENTNO.-8
AIM:Implementationofresourceallocationgraph(RAG).
Procedure:
The resource allocation graph is a graphical representation of a system's status.As the name
implies, theresourceallocationgraphcontainsallofthe information about allof the
processes holding some resources or waiting for some resources.It also contains
information on all instances of all resources, whether they are accessible or in use by
the processes.
Vertices
InRAG verticesaretwotypes–
1. Processvertex-EveryProcessisrepresentedasaprocessvertex.Theprocessis
generally represented by a circle.
2. Resourcevertex-Everyresourceisrepresentedasaresourcevertex. It
also has two types:
Singleinstancetyperesource:Itisrepresented asaboxwithonedotwithin.
Asaresult,thenumber ofdotsindicateshow manyinstancesofeachresourcetype are present.
Multi-resourceinstancetyperesource:It isalso representedasaboxwith multiple dots
within.
Algorithm:
1. First,findthecurrentlyavailableinstancesofeachresource.
2. Checkforeachprocesswhichcanbeexecutedusingtheallocated+availableresou
rce.
3. Addtheallocatedresourceoftheexecutableprocesstotheavailableresources and
terminate it.
4. Repeatthe2nd and 3rdstepsuntiltheexecutionofeachprocess.
5. Ifat anystep,noneoftheprocessescanbeexecutedthenthereisadeadlock in the
system.
Code/
Method:#include<s
tdio.h>#include<stdl
ib.h>#include<sys/
wait.h>#include<uni
std.h>void
waitexample()
{
int i,
stat;pid_tpid
[5];
for(i=0;i<5;i++)
52
{
53
if((pid[i] =fork())==0)
{
sleep(1);exit(1
00+i);
}
}
//Usingwaitpid()andprintingexitstatus
//of
children.for(i=0;i<
5:i++)
{
pid_tcpid=waitpid(pid[i],&stat,0); if
(WIFEXITED(stat))
printf("Child%dterminatedwithstatus:%d\
n",cpid,WEXITSTATUS(stat));
}
}
intmain()
{
waitexample();
return0;
}
Output:
VivaQuestions
1) Whatdoyouunderstandbycomputingresource?
2) DiscusstypesofverticesinRAG.
3) Comparesingleandmulti-instanceresourcetype.
4) Explainresourceallocationgraph.
5) HowRAGhelpsfordetectionofdeadlock?
54
EXPERIMENTNO.-9
AIM:ImplementationofBanker’salgorithm.
Procedure:
Deadlockavoidance&DeadLockPrevention:
Whenanewprocessentersasystem,itmustdeclarethemaximumnumberofinstances
ofeachresourcetypeitneeded.Thisnumbermayexceedthetotalnumberofresources in the
system. When the user requests a set of resources, the system must determine
whethertheallocationofeachresourcewillleavethesysteminsafestate.Ifit willthe
resources are allocation; otherwise, the process must wait until someother process
release the resources.
Datastructures
• n-Numberofprocesses,m-numberofresourcetypes.
• Available:Available[j]=k,k–instanceofresourcetypeRjisavailable.
• Max:Ifmax[i,j]=k, PimayrequestatmostkinstancesresourceRj.
• Allocation:IfAllocation[i, j]=k, Piallocatedto kinstancesofresourceRj
• Need:IfNeed[I,j]=k,Pimayneedk moreinstancesofresourcetype Rj,
Need[I, j]=Max[I, j]-Allocation[I, j];
Algorithm:
SafetyAlgorithm:
1. WorkandFinishbethevectoroflengthmandnrespectively,
Work=Available and Finish[i] =False.
2. Findanisuchthatboth
• Finish[i]=False
• Need<=Work
IfnosuchIexistsgo tostep4.
3. work=work+Allocation,Finish[i]=True;
4. ifFinish[1]=TrueforallI,thenthesystemisinsafestate.
Resourcerequestalgorithm:
55
2. ifRequest<=Availablegotostep3.OtherwisePimustsincethe
resources are available.
3. Havethesystempretendto haveallocatedtherequestedresourcesto
process Pi by modifying the state as follows;
Available=Available-RequestI;AllocationI=Allocation+RequestI;Needi=Needi-
Request I;
Iftheresultingresourceallocationstateissafe,thetransactioniscompletedandprocess
Piisallocateditsresources.However,ifthestateisunsafe,thePimustwaitforRequest i and
the old resource-allocation state is restored.
Code/Method:
/*BANKER’SALGORITHM*/
#include<stdio.h>#include<conio.h>structda
{
intmax[10],a1[10],need[10],before[10],after[10];
}p[10];
voidmain()
{
int i,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0; clrscr();printf("\n
ENTER THE NO. OF PROCESSES:");
scanf("%d",&n);
printf("\nENTERTHENO.OFRESOURCES:");
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].a1[j]);p[i].need[j]=p[i].max[j]-p[i].a1[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].a1[i];av[i]=tot[i]-temp;temp=0;
56
}
printf("\n\tRESOURCESALLOCATEDNEEDEDTOTALAVAIL");
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].a1[j]);
printf("\t");for(j=0;j<r;j++)
printf("%d",p[i].need[j]);
printf("\t");for(j=0;j<r;j++)
{
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("\nP%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
57
{
cn=0;cz=0;
}
}
}
if(c==n)
printf("\nTHEABOVE SEQUENCEISASAFESEQUENCE");
else
printf("\nDEADLOCKOCCURED");
getch();
}
Output:
ENTERTHENO.OFRESOURCES:3
PROCESS 1
MAXIMUMVALUEFORRESOURCE1:3
MAXIMUMVALUEFORRESOURCE2:2
MAXIMUMVALUEFORRESOURCE3:2
ALLOCATED FROM RESOURCE 1:1
ALLOCATEDFROMRESOURCE2:0
ALLOCATEDFROMRESOURCE3: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
PROCESS 4
MAXIMUMVALUEFORRESOURCE1:4
MAXIMUMVALUEFORRESOURCE2:2
58
MAXIMUMVALUEFORRESOURCE3:2
ALLOCATED FROM RESOURCE 1:0
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:2
ENTERTOTALVALUEOFRESOURCE1:9
ENTERTOTALVALUEOFRESOURCE2:3
ENTERTOTALVALUEOFRESOURCE3:6
RESOURCESALLOCATEDNEEDED TOTALAVAIL
P1 322 100 222 936
112
P2 613 511 102
AVAILBEFOREAVAILAFTER
P2 010 623
P1 401 723
P3 620 934
P4 514 936
THEABOVESEQUENCEISASAFESEQ
UENCE
VivaQuestions
1.) Whatismeant byDeadlock?
2.) WhatissafestateinBanker’sAlgorithm?
3.) WhatisBanker’salgorithm?
4.) Whatarenecessaryconditionsfordeadlock?
5.) Whatareprinciplesandgoalsofprotection?
59
EXPERIMENTNO.-10
Procedure:
One such deadlock detection algorithm makes use of a wait-for graph to track which other
processes a process is currently blocking on. In a wait-for graph, processes are
representedasnodes,andanedgefromprocessPitoPjimpliesPjisholdingaresource
thatPineedsandthusPiiswaitingforPjtoreleaseitslockonthatresource.Theremay
beprocesseswaitingformorethanasingleresourcetobecomeavailable.Graphcycles
imply the possibility of a deadlock.
Code/Method:
STEPSTOPERFORM:
(i) IdentifythewaitingprocessesintheRAG.
(ii) AccordinglydrawWait-forgraphforthegivenRAG.
(iii) Todrawitasgraphicalrepresentation,weintroducegraphics.hand work
in graphics mode.
(iv) Geometricimagesareenteredbyenteringgraphics,providingwith
parameter and closing graphics.
(v) Wenowidentifycircularchainofdependency(i.e.,appearanceof loops
in the graph)
Output:
Thewait-for-graph(graphicalrepresentation).Also,checkpresenceofloop.
VivaQuestions
1) DiscusstheconversionofRAGtoWFG.
2) Howcanyoudetectdeadlockusingwaitforgraph?
3) Explaintheprocessofdeadlockrecovery.
4) Howdeadlockcanbe prevented oravoided?
5) Explainthenecessaryconditions fordeadlock.
60
EXPERIMENTNO.-11
Procedure:
Producer consumer problemisa synchronizationproblem. There isa fixed size buffer where
the producer produces items and that is consumed bya consumer process. One
solution to the producer- consumer problem uses shared memory. To allow producer
and consumer processes to run concurrently, there must be available a buffer of
items thatcanbefilledbytheproducerandemptiedbytheconsumer.Thisbufferwillreside
in a region of memory that is shared by the producer and consumer processes. The
producer and consumer must be synchronized, so that the consumer does not try to
consume an item that has not yet been produced.
Code/Method:
#include<stdio.h>#includ
e<stdlib.h>
//Initializeamutexto1
intmutex=1;
//Numberoffullslotsas0
intfull=0;
//Numberofemptyslotsassize
//ofbuffer
intempty=10,x=0;
//Functiontoproduceanitemand
//addittothebuffer
voidproducer()
{
//Decreasemutexvalueby1
--mutex;
//Increasethenumberoffull
//slotsby1
++full;
//Decreasethenumberofempty
//slotsby1
--empty;
61
//
Itemproducedx
++;
printf("\
nProducerproduces""item
%d",
x);
//Increasemutexvalueby1
++mutex;
}
//Functiontoconsumeanitemand
//removeitfrombuffer
voidconsumer()
{
//Decreasemutexvalueby1
--mutex;
//Decreasethenumberoffull
//slotsby1
--full;
//Increasethenumberofempty
//slotsby1
++empty;
printf("\
nConsumerconsumes""item
%d",
x);
x--;
//Increasemutexvalueby1
++mutex;
}
//DriverCode
intmain()
{
intn,i;
printf("\
n1.Press1forProducer""\n2.
Press 2 for Consumer""\n3.
Press 3 for Exit");
//Using'#pragmaompparallelfor'
//cangivewrongvaluedueto
//synchronizationissues.
62
//'critical'specifiesthatcodeis
//executedbyonlyonethreadata
//timei.e.,onlyonethreadenters
63
//thecriticalsectionat agiventime #pragma
omp critical
for(i=1;i>0;i++){
printf("\nEnteryourchoice:");
scanf("%d",&n);
//
SwitchCasess
witch(n)
{case1:
//Ifmutexis1andempty
//isnon-zero,thenitis
//possibletoproduce
if((mutex==1)
&&(empty!=0))
{producer();
}
//Otherwise,printbuffer
//isfull
else{
printf("Bufferisfull!");
}
brea
k;case2
//Ifmutexis1andfull
//isnon-zero,thenitis
//possibletoconsume
if((mutex ==
1)&&(full!=0))
{consumer();
}
//Otherwise,printBuffer
//isempty
else{
printf("Bufferisempty!");
}
break;
64
//ExitCondition
case3:
exit(0
);brea
k;
65
}
}
}
Output:
VivaQuestions
1) Whatisbounded bufferproblem?
2) Whatisprocesssynchronization?
3) Whatiscriticalsection?
4) Whatisframebuffer?
5) ExplainMutualExclusion.
66
EXPERIMENTNO.-12
Procedure:
The readers-writers problem relates to an object such as a file that is shared between
multipleprocesses.Someoftheseprocessesarereadersi.e.,theyonlywanttoreadthe data
fromthe object and some ofthe processes are writers i.e., theywant to write into the
object.
The readers-writers problem is used to manage synchronization so that there are no
problems with the object data. For example - If two readers access the object at the
same time there is no problem. However, if two writers or a reader and writer access
the object at the same time, there may be problems.
To solve this situation, a writer should get exclusive access to an object i.e., when a writer is
accessing the object, no reader or writer may access it. However, multiple readers
can access the object at the same time.
Code/
Method:#include<sem
aphore.h>#include<std
io.h>#include<stdlib.h
>sem_t x,y;
pthread_ttid;
pthread_twriterthreads[100],readerthreads[100];int
readercount;
void*reader(void*param)
{
sem_wait(&x);
readercount+
+;if(readercount==1
)sem_wait(&y);
sem_post(&x);
printf("\n
%dreaderisinside",readercount);sem_wait
(&x);
readercount--;if(readercoun
t==0)
{
sem_post(&y);
}
sem_post(&x);
printf("\n%dReaderisleaving",readercount+1);
}
void*writer(void*param)
67
{
printf("\
nWriteristryingtoenter");sem_wait(&y);
printf("\nWriterhasentered");
sem_post(&y);printf("\
nWriter is leaving");
}
intmain()
{
intn2,i;
printf("Enterthenumberofreaders:");sca
nf("%d",&n2);
int
n1[n2];sem_init
(&x,0,1);
sem_init(&y,0,1
);
for(i=0;i<n2;i+
+)
{
pthread_create(&writerthreads[i],NULL,reader,NULL);
pthread_create(&readerthreads[i],NULL,writer,NULL);
}
for(i=0;i<n2;i++)
{
pthread_join(writerthreads[i],NULL);pthread_join(readerthreads[i],NUL
L);
}
Output:
reader is
insidereaderisl
eavingreader
is inside
readerisleavin
g
writeristryingtoenter
writer has entered
writer is leaving
VivaQuestions
1) Whatiscriticalsectionproblem?
2) Whatissemaphore?
3) Defineconcurrentprocess.
68
4) Whatisreaderwriterproblem?
5) DefineVariousApplicationofsemaphore.
69