You are on page 1of 68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

BCA NOTES
HOME

BUSINESS

DOWNLOADS

PARENTCATEGORY

THINGSYOUMUSTSHARE

Operatingsystemforbcafullrefrence
17:04

ABOUTUS

SOCIALPROFILES

Nocomments

OperatingSystem

Search

CHAPTER1SYSTEMSOFTWARE
CHAPTER2FUNDAMENTALOFOPERATINGSYSTEM

Popular

Tags

BlogArchives

BCANOTES.PoweredbyBlogger.

CHAPTER3PROCESSMANAGEMENT
CHAPTER4THREADMANAGEMENT

BLOGARCHIVE

CHAPTER5CONCURRENCYCONTROL

2016(1)

CHAPTER6DEADLOCK

2015(15)

CHAPTER7MEMORYMANAGEMENT

2014(172)
December(17)

CHAPTER8VIRTUALMEMORY

November(1)

CHAPTER9I/OHARDWARE

October(11)

CHAPTER10I/OSOFTWARE

August(8)

CHAPTER11SECONDARYSTORAGEMANAGEMENT

July(3)
June(5)

CHAPTER12FILESYSTEMS

May(42)
Trythishtmldownloadcoding

CHAPTER13PROTECTION
CHAPTER14SECURITY

Pleasegothislinktoknowabout
communication

CHAPTER15LINUXSYSTEM

MatsuniversitysyllabusforBCAIIsem
mttr
RAMchips

CHAPTER1

SYSTEMSOFTWARE
UnitStructure
1.0Objectives
1.1Introduction

Interruproutinevssubroutine
Q.2WhatisBUS?Whatarethedifferent
busesused...
Q.1WhatisComputerArchitecture?What
isstored...
Q.Whichlogicnameorgatesareknownas
universa...
Q.Whatisshiftregisterindigitalcomputer.

1.2OperatingSystem

Whatitsgraycode?

1.2.1Definitionofoperatingsystem

Q.Whatistheconceptoflayersin
architectural...

1.2.2FunctionsofOperatingSystem

Q.WhatisComputerOrganisation?

1.2.3OperatingSystemasUserInterface

Q.WhatisComputerArchitecture?
Whatarethedifferenttypesofmappings
usedinc...

1.3I/OSystemManagement
1.4Assembler

Whatarethedifferenttypesofmappings
usedinc...
No.RISCCISC1...

1.5Compiler

DifferenceBetweenRISCandCISC

1.6Loader

DifferenceBetweenRISCandCISC

1.7HistoryofOperatingSystem
1.8Summary
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

PAPERSAMPLEFORCOMPUTER
ARCHITECTUREANDORGANIZ...
whatisindirectaddressingmode?

1/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

1.9ModelQuestion

whatistheformatoffloatingpoint
representatio...
TrythiscodingHTML
WhatisanEntityRelationshipdiagram?
MitigationofNoisepollution
Preventionofsoilerosion

1.0Objectives
Aftergoingthroughthisunit,youwillbeableto:
DescribeBasicOrganizationofComputerSystems
DefineOperatingsystem,functions,historyandEvolution
Defineassembler,linker,loader,compiler

1.1Introduction

Soilerosionanditsprevention
PreventionandControlofWaterPollution
DangersofWaterPollution
Waterpollutionpreventionandcontrol
Groundlevelfightagainstairpollution
Generalairpollutioncontroldevices/
equipments...
Methodstocontrolparticulateemissions

Anoperatingsystemactasanintermediarybetweentheuserofacomputer
andcomputerhardware.Thepurposeofanoperatingsystemistoprovidean
environmentinwhichausercanexecuteprogramsinaconvenientandefficient
manner.
Anoperatingsystemisasoftwarethatmanagesthecomputerhardware.The
hardwaremustprovideappropriatemechanismstoensurethecorrectoperation
of
thecomputersystemandtopreventuserprogramsfrominterferingwiththe
proper
operationofthesystem.

Fundamentalsofpreventionandcontrolof
airpoll...
Noisepollution
Soilpollution(Landdegradation):
Controloverwaterpollution
Waterpollutionbyindustriesanditseffects
WaterPollution
HarmfulEffectsofairpollution
Environmentalpollution
Operatingsystemforbcafullrefrence

1.2OperatingSystem

April(6)

1.2.1DefinitionofOperatingSystem:

March(50)

AnOperatingsystemisaprogramthatcontrolstheexecutionofapplication
programsandactsasaninterfacebetweentheuserofacomputerandthe
computerhardware.
Amorecommondefinitionisthattheoperatingsystemistheoneprogram
runningatalltimesonthecomputer(usuallycalledthekernel),withallelse
beingapplicationsprograms.

February(14)
January(15)
2013(752)

AnOperatingsystemisconcernedwiththeallocationofresourcesand
services,suchasmemory,processors,devicesandinformation.The
OperatingSystemcorrespondinglyincludesprogramstomanagethese
resources,suchasatrafficcontroller,ascheduler,memorymanagement
module,I/Oprograms,andafilesystem.
1.2.2FunctionsofOperatingSystem
Operatingsystemperformsthreefunctions:
1.Convenience:AnOSmakesacomputermoreconvenienttouse.
2.Efficiency:AnOSallowsthecomputersystemresourcestobeusedinan
efficientmanner.
3.AbilitytoEvolve:AnOSshouldbeconstructedinsuchawayastopermit
theeffectivedevelopment,testingandintroductionofnewsystemfunctions
withoutatthesametimeinterferingwithservice.
1.2.3OperatingSystemasUserInterface
Everygeneralpurposecomputerconsistsofthehardware,operatingsystem,
systemprograms,applicationprograms.Thehardwareconsistsofmemory,
CPU,ALU,I/Odevices,peripheraldeviceandstoragedevice.System
programconsistsofcompilers,loaders,editors,OSetc.Theapplication
programconsistsofbusinessprogram,databaseprogram.
Everycomputermusthaveanoperatingsystemtorunotherprograms.The
operatingsystemandcoordinatestheuseofthehardwareamongthevarious
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

2/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

systemprogramsandapplicationprogramforavarioususers.Itsimply
providesanenvironmentwithinwhichotherprogramscandousefulwork.
Theoperatingsystemisasetofspecialprogramsthatrunonacomputer
systemthatallowittoworkproperly.Itperformsbasictaskssuchas
recognizinginputfromthekeyboard,keepingtrackoffilesanddirectories
onthedisk,sendingoutputtothedisplayscreenandcontrollingaperipheral
devices.
OSisdesignedtoservetwobasicpurposes:
1.Itcontrolstheallocationanduseofthecomputingsystem'sresourcesamong
thevarioususerandtasks.
2.Itprovidesaninterfacebetweenthecomputerhardwareandtheprogrammer
thatsimplifiesandmakesfeasibleforcoding,creation,debuggingof
applicationprograms.
Theoperatingsystemmustsupportthefollowingtasks.Thetasksare:
1.Providesthefacilitiestocreate,modificationofprogramanddatafilesusing
andeditor.
2.Accesstothecompilerfortranslatingtheuserprogramfromhighlevel
languagetomachinelanguage.
3.Providealoaderprogramtomovethecompiledprogramcodetothe
computer'smemoryforexecution.
4.ProvideroutinesthathandlethedetailsofI/Oprogramming.

1.3I/OSystemManagement
I/OSystemManagement
ThemodulethatkeepstrackofthestatusofdevicesiscalledtheI/Otraffic
controller.EachI/Odevicehasadevicehandlerthatresidesinaseparate
processassociatedwiththatdevice.
TheI/Osubsystemconsistsof
1.Amemorymanagementcomponentthatincludesbuffering,cachingand
spooling.
2.Ageneraldevicedriverinterface.
Driversforspecifichardwaredevices.

1.4Assembler
Inputtoanassemblerisanassemblylanguageprogram.Outputisanobject
programplusinformationthatenablestheloadertopreparetheobjectprogram
for
execution.Atonetime,thecomputerprogrammerhadathisdisposalabasic
machinethatinterpreted,throughhardware,certainfundamentalinstructions.He
wouldprogramthiscomputerbywritingaseriesofonesandzeros(machine
language),placethemintothememoryofthemachine.

1.5Compiler
ThehighlevellanguagesexamplesareFORTRAN,COBOL,ALGOLand
PL/I
areprocessedbycompilersandinterpreters.Acompilersisaprogramthat
acceptsasourceprograminahighlevellanguageandproducesa
corresponding
objectprogram.Aninterpreterisaprogramthatappearstoexecuteasource
programasifitwasmachinelanguage.Thesamename(FORTRAN,COBOL
etc)
isoftenusedtodesignatebothacompileranditsassociatedlanguage.

1.6Loader
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

3/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Aloaderisaroutinethatloadsanobjectprogramandpreparesitforexecution.
Therearevariousloadingschemes:absolute,relocatinganddirectlinking.In
general,theloadermustload,relocate,andlinktheobjectprogram.Loaderisa
programthatplacesprogramsintomemoryandpreparesthemforexecution.In
a
simpleloadingscheme,theassembleroutputsthemachinelanguagetranslation
of
aprogramonasecondarydeviceandaloaderisplacedincore.Theloader
places
intomemorythemachinelanguageversionoftheuser'sprogramandtransfers
controltoit.Sincetheloaderprogramismuchsmallerthantheassembler,thos
makesmorecoreavailabletouser'sprogram.

1.7HistoryofOperatingSystem
Operatingsystemshavebeenevolvingthroughtheyears.Followingtable
showsthehistoryofOS.
GenerationYearElectronicdevicesusedTypesofOSanddevices
First194555VacuumtubesPlugboards
Second19551965TransistorsBatchsystem
Third19651980IntegratedCircuit(IC)Multiprogramming
FourthSince1980LargescaleintegrationPC

1.8Summary
OperatingSystems
AnOperatingsystemisconcernedwiththeallocationofresourcesandservices,
suchasmemory,processors,devicesandinformation.TheOperatingSystem
correspondinglyincludesprogramstomanagetheseresources,suchasatraffic
controller,ascheduler,memorymanagementmodule,I/Oprograms,andafile
system.
Assembler
Inputtoanassemblerisanassemblylanguageprogram.Outputisanobject
programplusinformationthatenablestheloadertopreparetheobjectprogram
for
execution.
Loader
Aloaderisaroutinethatloadsanobjectprogramandpreparesitforexecution.
Therearevariousloadingschemes:absolute,relocatinganddirectlinking.In
general,theloadermustload,relocate,andlinktheobjectprogram
Compilers
Acompilersisaprogramthatacceptsasourceprograminahighlevel
language
andproducesacorrespondingobjectprogram.

1.9ModelQuestion
Q.1DefineOperatingSystem?
Q.2Explainvariousfunctionofoperatingsystem?
Q.3ExplainI/OsystemManagement?
Q.4Define&explainAssembler,Loader,Compiler?

http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

4/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

CHAPTER2
FUNDAMENTALOFOPERATINGSYSTEM
UnitStructure
2.0Objectives
2.1Introduction
2.2OperatingSystemServices
2.3OperatingSystemComponents
2.4BatchSystem
2.5TimeSharingSystem
2.6Multiprogramming
2.7Spooling
2.8PropertiesofOperatingSystem
2.9Summary
2.10ModelQuestion

2.0Objectives
Aftergoingthroughthisunit,youwillbeableto:
Todescribetheservicesanoperatingsystemprovidestousers,processes,
andothersystems
Describeoperatingsystemservicesanditscomponents.
Definemultitaskingandmultiprogramming.
Describetimesharing,buffering&spooling.

2.1Introduction
Anoperatingsystemprovidestheenvironmentwithinwhichprogramsare
executed.Internally,operatingsystemsvarygreatlyintheirmakeup,sincethey
are
organizedalongmanydifferentlines.Thedesignofanewoperatingsystemisa
majortask.Itisimportantthatthegoalsofthesystembewelldefinedbeforethe
designbegins.
Wecanviewanoperatingsystemfromseveralvantagepoints.Oneview
focusesontheservicesthatthesystemprovides,another,ontheinterfacethatit
makesavailabletousersandprogrammersathird,onitscomponentsandtheir
interconnections.

2.2OperatingSystemServices
Anoperatingsystemprovidesservicestoprogramsandtotheusersofthose
programs.Itprovidedbyoneenvironmentfortheexecutionofprograms.
Theservicesprovidedbyoneoperatingsystemisdifficultthanother
operatingsystem.Operatingsystemmakestheprogrammingtaskeasier.
Thecommonserviceprovidedbytheoperatingsystemislistedbelow.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

5/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

1.Programexecution
2.I/Ooperation
3.Filesystemmanipulation
4.Communications
5.Errordetection
1.Programexecution:Operatingsystemloadsaprogramintomemoryand
executestheprogram.Theprogrammustbeabletoenditsexecution,either
normallyorabnormally.
2.I/OOperation:I/OmeansanyfileoranyspecificI/Odevice.Programmay
requireanyI/Odevicewhilerunning.Sooperatingsystemmustprovidethe
requiredI/O.
3.Filesystemmanipulation:Programneedstoreadafileorwriteafile.The
operatingsystemgivesthepermissiontotheprogramforoperationonfile.
4.Communication:Datatransferbetweentwoprocessesisrequiredforsome
time.Thebothprocessesareontheonecomputerorondifferentcomputer
butconnectedthroughcomputernetwork.Communicationmaybe
implementedbytwomethods:
a.Sharedmemory
b.Messagepassing.
5.Errordetection:errormayoccurinCPU,inI/Odevicesorinthememory
hardware.Theoperatingsystemconstantlyneedstobeawareofpossible
errors.Itshouldtaketheappropriateactiontoensurecorrectandconsistent
computing.
Operatingsystemwithmultipleusersprovidesfollowingservices.
1.ResourceAllocation
2.Accounting
3.Protection
A)ResourceAllocation:
Iftherearemorethanoneuserorjobsrunningatthesametime,then
resourcesmustbeallocatedtoeachofthem.Operatingsystemmanages
differenttypesofresourcesrequirespecialallocationcode,i.e.main
memory,CPUcyclesandfilestorage.
Therearesomeresourceswhichrequireonlygeneralrequestandrelease
code.ForallocatingCPU,CPUschedulingalgorithmsareusedforbetter
utilizationofCPU.CPUschedulingalgorithmsareusedforbetterutilization
ofCPU.CPUschedulingroutinesconsiderthespeedoftheCPU,numberof
availableregistersandotherrequiredfactors.

B)Accounting:
Logsofeachusermustbekept.Itisalsonecessarytokeeprecordofwhich
userhowmuchandwhatkindsofcomputerresources.Thislogisusedfor
accountingpurposes.
Theaccountingdatamaybeusedforstatisticsorforthebilling.Italsoused
toimprovesystemefficiency.
C)Protection:
Protectioninvolvesensuringthatallaccesstosystemresourcesiscontrolled.
Securitystartswitheachuserhavingtoauthenticatetothesystem,usually
bymeansofapassword.ExternalI/Odevicesmustbealsoprotectedfrom
invalidaccessattempts.
Inprotection,alltheaccesstotheresourcesiscontrolled.Inmultiprocess
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

6/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

environment,itispossiblethat,oneprocesstointerfacewiththeother,or
withtheoperatingsystem,soprotectionisrequired.

2.3OperatingSystemComponents
Modernoperatingsystemssharethegoalofsupportingthesystem
components.Thesystemcomponentsare:
1.ProcessManagement
2.MainMemoryManagement
3.FileManagement
4.SecondaryStorageManagement
5.I/OSystemManagement
6.Networking
7.ProtectionSystem
8.CommandInterpreterSystem

2.4BatchSystem
Somecomputersystemsonlydidonethingatatime.Theyhadalistofthe
computersystemmaybededicatedtoasingleprogramuntilitscompletion,
ortheymaybedynamicallyreassignedamongacollectionofactive
programsindifferentstagesofexecution.
Batchoperatingsystemisonewhereprogramsanddataarecollected
togetherinabatchbeforeprocessingstarts.Ajobispredefinedsequenceof
commands,programsanddatathatarecombinedintoasingleunitcalled
job.
Fig.2.1showsthememorylayoutforasimplebatchsystem.
Memorymanagementinbatchsystemisverysimple.Memoryisusuallydivided
intotwoareas:
1.Operatingsystemand
2.Userprogramarea.
Fig2.1MemoryLayoutforaSimpleBatchSystem
Operating
System
UserProgram
Area
Resident
Portion
Transient
Program

Schedulingisalsosimpleinbatchsystem.Jobsareprocessedintheorderof
submissioni.efirstcomefirstservedfashion.

Whenjobcompletedexecution,itsmemoryisreleasesandtheoutputforthe
jobgetscopiedintoanoutputspoolforlaterprinting.
Batchsystemoftenprovidessimpleformsoffilemanagement.Accesstofile
isserial.Batchsystemsdonotrequireanytimecriticaldevicemanagement.
Batchsystemsareinconvenientforusersbecauseuserscannotinteractwith
theirjobstofixproblems.Theremayalsobelongturnaroundtimes.
Exampleofthissystemidgeneratingmonthlybankstatement.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

7/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

AdvantagesoBatchSystem
Movemuchoftheworkoftheoperatortothecomputer.
Increasedperformancesinceitwaspossibleforjobtostartassoonasthe
previousjobfinished.
DisadvantagesofBatchSystem
Turnaroundtimecanbelargefromuserstandpoint.
Difficulttodebugprogram.
Ajobcouldenteraninfiniteloop.
Ajobcouldcorruptthemonitor,thusaffectingpendingjobs.
Duetolackofprotectionscheme,onebatchjobcanaffectpendingjobs.

2.5TimeSharingSystems
Multiprogrammedbatchedsystemsprovideanenvironmentwherethe
varioussystemresources(forexample,CPU,memory,peripheraldevices)
areutilizedeffectively.
Timesharing,ormultitasking,isalogicalextensionofmultiprogramming.
MultiplejobsareexecutedbytheCPUswitchingbetweenthem,butthe
switchesoccursofrequentlythattheusersmayinteractwitheachprogram
whileitisrunning.
Aninteractive,orhandson,computersystemprovidesonline
communicationbetweentheuserandthesystem.Theusergivesinstructions
totheoperatingsystemortoaprogramdirectly,andreceivesanimmediate
response.Usually,akeyboardisusedtoprovideinput,andadisplayscreen
(suchasacathoderaytube(CRT)ormonitor)isusedtoprovideoutput.
Ifusersaretobeabletoaccessbothdataandcodeconveniently,anonline
filesystemmustbeavailable.Afileisacollectionofrelatedinformation
definedbyitscreator.Batchsystemsareappropriateforexecutinglargejobs
thatneedlittleinteraction.
Timesharingsystemsweredevelopedtoprovideinteractiveuseofa
computersystematareasonablecost.Atimesharedoperatingsystemuses
CPUschedulingandmultiprogrammingtoprovideeachuserwithasmall
portionofatimesharedcomputer.Eachuserhasatleastoneseparate
programinmemory.Aprogramthatisloadedintomemoryandisexecuting
iscommonlyreferredtoasaprocess.Whenaprocessexecutes,ittypically
executesforonlyashorttimebeforeiteitherfinishesorneedstoperform
I/O.I/Omaybeinteractivethatis,outputistoadisplayfortheuserand
inputisfromauserkeyboard.SinceinteractiveI/Otypicallyrunsatpeople
speeds,itmaytakealongtimetocompleted.
Atimesharedoperatingsystemallowsthemanyuserstosharethecomputer
simultaneously.Sinceeachactionorcommandinatimesharedsystem
tendstobeshort,onlyalittleCPUtimeisneededforeachuser.Asthe
systemswitchesrapidlyfromoneusertothenext,eachuserisgiventhe
impressionthatshehasherowncomputer,whereasactuallyonecomputeris
beingsharedamongmanyusers.
Timesharingoperatingsystemsareevenmorecomplexthanare
multiprogrammed
operatingsystems.Asinmultiprogramming,severaljobsmust
bekeptsimultaneouslyinmemory,whichrequiressomeformofmemory
managementandprotection.

2.6Multiprogramming
Whentwoormoreprogramsareinmemoryatthesametime,sharingthe
processorisreferredtothemultiprogrammingoperatingsystem.
Multiprogrammingassumesasingleprocessorthatisbeingshared.It
increasesCPUutilizationbyorganizingjobssothattheCPUalwayshasone
toexecute.

http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

8/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Fig.2.2
showsthememorylayoutforamultiprogrammingsystem.
Theoperatingsystemkeepsseveraljobsinmemoryatatime.Thissetof
jobsisasubsetofthejobskeptinthejobpool.Theoperatingsystem
picksandbeginstoexecuteoneofthejobinthememory.
Multiprogrammedsystemprovideanenvironmentinwhichthevarious
systemresourcesareutilizedeffectively,buttheydonotprovideforuser
interactionwiththecomputersystem.
Jobsenteringintothesystemarekeptintothememory.Operatingsystem
picksthejobandbeginstoexecuteoneofthejobinthememory.Having
severalprogramsinmemoryatthesametimerequiressomeformof
memorymanagement.
Multiprogrammingoperatingsystemmonitorsthestateofallactive
programsandsystemresources.ThisensuresthattheCPUisneveridle
unlesstherearenojobs.
Advantages
1.HighCPUutilization.
2.ItappearsthatmanyprogramsareallottedCPUalmostsimultaneously.
Disadvantages
1.CPUschedulingisrequires.
2.Toaccommodatemanyjobsinmemory,memorymanagementisrequired.

2.7Spooling
Acronymforsimultaneousperipheraloperationsonline.Spoolingrefersto
puttingjobsinabuffer,aspecialareainmemoryoronadiskwhereadevice
canaccessthemwhenitisready.
Spoolingisusefulbecausedeviceaccessdatathatdifferentrates.Thebuffer
providesawaitingstationwheredatacanrestwhiletheslowerdevice
catchesup.Fig2.3showsthespooling.
Fig2.3SpoolingProcess
ComputercanperformI/Oinparallelwithcomputation,itbecomespossible
tohavethecomputerreadadeckofcardstoatape,drumordiskandto
writeouttoatapeprinterwhileitwascomputing.Thisprocessiscalled
spooling.
DISK
CARD
READER
PRINTER

Themostcommonspoolingapplicationisprintspooling.Inprintspooling,
documentsareloadedintoabufferandthentheprinterpullsthemoffthe
bufferatitsownrate.
Spoolingisalsousedforprocessingdataatremotesites.TheCPUsendsthe
dataviacommunicationspathtoaremoteprinter.SpoolingoverlapstheI/O
ofonejobwiththecomputationofotherjobs.
Onedifficultywithsimplebatchsystemsisthatthecomputerstillneedsto
readthedecksofcardsbeforeitcanbegintoexecutethejob.Thismeans
thattheCPUisidleduringtheserelativelyslowoperations.
Spoolingbatchsystemswerethefirstandarethesimplestofthe
multiprogrammingsystems.
AdvantageofSpooling
1.Thespoolingoperationusesadiskasaverylargebuffer.
2.SpoolingishowevercapableofoverlappingI/Ooperationforonejobwith
processoroperationsforanotherjob.

2.8EssentialPropertiesoftheOperatingSystem
1.Batch:Jobswithsimilarneedsarebatchedtogetherandrunthroughthe
computerasagroupbyanoperatororautomaticjobsequencer.Performanceis
increasedbyattemptingtokeepCPUandI/Odevicesbusyatalltimesthrough
buffering,offlineoperation,spoolingandmultiprogramming.ABatchsystem
is
goodforexecutinglargejobsthatneedlittleinteraction,itcanbesubmittedand
pickeduplatter.
2.Timesharing:UsesCPUsschedulingandmultiprogrammingtoprovide
economicalinteractiveuseofasystem.TheCPUswitchesrapidlyfromoneuser
to
anotheri.e.theCPUissharedbetweenanumberofinteractiveusers.Insteadof
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

9/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

havingajobdefinedbyspooledcardimages,eachprogramreadsitsnext
control
instructionsfromtheterminalandoutputisnormallyprintedimmediatelyonthe
screen.
3.Interactive:Userisonlinewithcomputersystemandinteractswithitviaan
interface.Itistypicallycomposedofmanyshorttransactionswheretheresultof
thenexttransactionmaybeunpredictable.Responsetimeneedstobeshortsince
theusersubmitsandwaitsfortheresult.
4.Realtimesystem:Realtimesystemsareusuallydedicated,embedded
systems.
Theytypicallyreadfromandreacttosensordata.Thesystemmustguarantee
responsetoeventswithinfixedperiodsoftimetoensurecorrectperformance.
5.Distributed:Distributescomputationamongseveralphysicalprocessors.
The
processorsdonotsharememoryoraclock.Instead,eachprocessorhasitsown
localmemory.Theycommunicatewitheachotherthroughvarious
communication
lines.

2.9Summary
Anoperatingsystemprovidesservicestoprogramsandtotheusersof
thoseprograms.Itprovidedbyoneenvironmentfortheexecutionofprograms.
Theservicesprovidedbyoneoperatingsystemisdifficultthanotheroperating
system.Operatingsystemmakestheprogrammingtaskeasier.
Batchoperatingsystemisonewhereprogramsanddataarecollected
togetherinabatchbeforeprocessingstarts.Inbatchoperatingsystemmemoryis
usuallydividedintotwoareas:Operatingsystemanduserprogramarea.
Timesharing,ormultitasking,isalogicalextensionofmultiprogramming.
MultiplejobsareexecutedbytheCPUswitchingbetweenthem,butthe
switches
occursofrequentlythattheusersmayinteractwitheachprogramwhileitis
running.
Whentwoormoreprogramsareinmemoryatthesametime,sharingthe
processorisreferredtothemultiprogrammingoperatingsystem.
Spoolingisusefulbecausedeviceaccessdatathatdifferentrates.Thebuffer
providesawaitingstationwheredatacanrestwhiletheslowerdevicecatches
up.

2.10ModelQuestion
Q.1Explainvariousoperatingsystemservices?
Q.2DefineSpooling?DescribeSpoolingprocess?
Q.3DifferentiateMultitasking&Multiprogramming?

CHAPTER3
PROCESSMANAGEMENT
UnitStructure
3.0Objectives
3.1ConceptofProcess
3.1.1ProcessesandPrograms
3.2ProcessState
3.2.1SuspendedProcesses
3.2.2ProcessControlBlock
3.3ProcessManagement
3.3.1SchedulingQueues
3.3.2Schedulers
3.4ContextSwitching
3.5Operationonprocesses
3.6CooperatingProcesses
3.7Summary
3.8ModelQuestion

3.0Objectives
Aftergoingthroughthisunit,youwillbeableto:
Tointroducethenotionofaprocessaprograminexecution,whichforms
thebasisofallcomputation
Todescribethevariousfeaturesofprocesses,includingscheduling,creation
andtermination,andcommunication.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

10/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

3.1ConceptofProcess
Aprocessissequentialprograminexecution.Aprocessdefinesthe
fundamentalunitofcomputationforthecomputer.Componentsofprocess
are:
1.ObjectProgram
2.Data
3.Resources
4.Statusoftheprocessexecution.
Objectprogrami.e.codetobeexecuted.Dataisusedforexecutingthe
program.Whileexecutingtheprogram,itmayrequiresomeresources.Last
componentisusedforverifyingthestatusoftheprocessexecution.A
processcanruntocompletiononlywhenallrequestedresourceshavebeen
allocatedtotheprocess.Twoormoreprocessescouldbeexecutingthesame
program,eachusingtheirowndataandresources.

3.1.1ProcessesandPrograms
Processisadynamicentity,thatisaprograminexecution.Aprocessisa
sequenceofinformationexecutions.Processexistsinalimitedspanoftime.
Twoormoreprocessescouldbeexecutingthesameprogram,eachusing
theirowndataandresources.
Programisastaticentitymadeupofprogramstatement.Programcontains
theinstructions.Aprogramexistsatsingleplaceinspaceandcontinuesto
exist.Aprogramdoesnotperformtheactionbyitself.

3.2ProcessState
Whenprocessexecutes,itchangesstate.Processstateisdefinedasthe
currentactivityoftheprocess.Fig.3.1showsthegeneralformofthe
processstatetransitiondiagram.Processstatecontainsfivestates.Each
processisinoneofthestates.Thestatesarelistedbelow.
1.New
2.Ready
3.Running
4.Waiting
5.Terminated(exist)
1.New:Aprocessthatjustbeencreated.
2.Ready:Readyprocessesarewaitingtohavetheprocessorallocatedtothem
bytheoperatingsystemsothattheycanrun.
3.Running:Theprocessthatiscurrentlybeingexecuted.Arunningprocess
possessesalltheresourcesneededforitsexecution,includingtheprocessor.
4.Waiting:Aprocessthatcannotexecuteuntilsomeeventoccurssuchasthe
completionofanI/Ooperation.Therunningprocessmaybecomesuspended
byinvokinganI/Omodule.
5.Terminated:Aprocessthathasbeenreleasedfromthepoolofexecutable
processesbytheoperatingsystem.
Fig3.1DiagramforProcessState
Wheneverprocesseschangesstate,theoperatingsystemreactsbyplacing
theprocessPCBinthelistthatcorrespondstoitsnewstate.Onlyone
processcanberunningonanyprocessoratanyinstantandmanyprocesses
maybereadyandwaitingstate.

3.2.1SuspendedProcesses
Characteristicsofsuspendprocess
1.Suspendedprocessisnotimmediatelyavailableforexecution.
2.Theprocessmayormaynotbewaitingonanevent.
3.Forpreventingtheexecution,processissuspendbyOS,parentprocess,
processitselfandanagent.
4.Processmaynotberemovedfromthesuspendedstateuntiltheagentorders
theremoval.
Swappingisusedtomoveallofaprocessfrommainmemorytodisk.When
alltheprocessbyputtingitinthesuspendedstateandtransferringittodisk.
Reasonsforprocesssuspension
1.Swapping
2.Timing
3.Interactiveuserrequest
4.Parentprocessrequest

http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

11/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Swapping:OSneedstoreleaserequiredmainmemorytobringinaprocessthat
is
readytoexecute.
Timing:Processmaybesuspendedwhilewaitingforthenexttimeinterval.
Interactiveuserrequest:Processmaybesuspendedfordebuggingpurposeby
user.
Parentprocessrequest:Tomodifythesuspendedprocessortocoordinatethe
activityofvariousdescendants.

3.2.2ProcessControlBlock(PCB)
Eachprocesscontainstheprocesscontrolblock(PCB).PCBisthedata
structureusedbytheoperatingsystem.Operatingsystemgroupsall
informationthatneedsaboutparticularprocess.Fig.3.2showstheprocess
controlblock.
Pointer
Process
State
ProcessNumber
ProgramCounter
CPUregisters
MemoryAllocation
EventInformation
Listofopenfiles
Fig.3.2ProcessControlBlock
1.Pointer:Pointerpointstoanotherprocesscontrolblock.Pointerisusedfor
maintainingtheschedulinglist.
2.ProcessState:Processstatemaybenew,ready,running,waitingandsoon.
3.ProgramCounter:Itindicatestheaddressofthenextinstructiontobe
executedforthisprocess.
4.Eventinformation:Foraprocessintheblockedstatethisfieldcontains
informationconcerningtheeventforwhichtheprocessiswaiting.
5.CPUregister:Itindicatesgeneralpurposeregister,stackpointers,index
registersandaccumulatorsetc.numberofregisterandtypeofregistertotally
dependsuponthecomputerarchitecture.
6.MemoryManagementInformation:Thisinformationmayincludethevalue
ofbaseandlimitregister.Thisinformationisusefulfordeallocatingthe
memorywhentheprocessterminates.
7.AccountingInformation:ThisinformationincludestheamountofCPUand
realtimeused,timelimits,joborprocessnumbers,accountnumbersetc.
ProcesscontrolblockalsoincludestheinformationaboutCPUscheduling,
I/Oresourcemanagement,filemanagementinformation,priorityandsoon.
ThePCBsimplyservesastherepositoryforanyinformationthatmayvary
fromprocesstoprocess.
Whenaprocessiscreated,hardwareregistersandflagsaresettothevalues
providedbytheloaderorlinker.Wheneverthatprocessissuspended,the
contentsoftheprocessorregisterareusuallysavedonthestackandthe
pointertotherelatedstackframeisstoredinthePCB.Inthisway,the
hardwarestatecanberestoredwhentheprocessisscheduledtorunagain.

3.3ProcessManagement/ProcessScheduling
Multiprogrammingoperatingsystemallowsmorethanoneprocesstobe
loadedintotheexecutablememoryatatimeandfortheloadedprocessto
sharetheCPUusingtimemultiplexing.
Theschedulingmechanismisthepartoftheprocessmanagerthathandles
theremovaloftherunningprocessfromtheCPUandtheselectionof
anotherprocessonthebasisofparticularstrategy.
3.3.1SchedulingQueues
Whentheprocessentersintothesystem,theyareputintoajobqueue.This
queueconsistsofallprocessesinthesystem.Theoperatingsystemalsohas
otherqueues.
Devicequeueisaqueueforwhichalistofprocesseswaitingforaparticular
I/Odevice.Eachdevicehasitsowndevicequeue.Fig.3.3showsthe
queuingdiagramofprocessscheduling.Inthefig3.3,queueisrepresented
byrectangularbox.Thecirclesrepresenttheresourcesthatservethequeues.
Thearrowsindicatetheflowofprocessesinthesystem.
Fig.3.3QueuingDiagram
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

12/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Queuesareoftwotypes:readyqueueandsetofdevicequeues.A
newlyarrivedprocessisputinthereadyqueue.Processesarewaiting
inreadyqueueforallocatingtheCPU.OncetheCPUisassignedto
theprocess,thenprocesswillexecute.Whileexecutingtheprocess,
oneoftheseveraleventscouldoccur.
1.TheprocesscouldissueanI/OrequestandthenplaceinanI/O
queue.
2.Theprocesscouldcreatenewsubprocessandwaitsforits
termination.
3.TheprocesscouldberemovedforciblyfromtheCPU,asaresult
ofinterruptandputbackinthereadyqueue.
3.3.1.1TwoStateProcessModel
Processmaybeinoneoftwostates:
a)Running
b)NotRunning
whennewprocessiscreatedbyOS,thatprocessentersintothe
systemintherunningstate.
Processesthatarenotrunningarekeptinqueue,waitingtheirturnto
execute.Eachentryinthequeueisaprintertoaparticularprocess.
Queueisimplementedbyusinglinkedlist.Useofdispatcherisas
follows.Whenaprocessinterrupted,thatprocessistransferredinthe
waitingqueue.Iftheprocesshascompletedoraborted,theprocessis
discarded.Ineithercase,thedispatcherthenselectaprocessfromthe
queuetoexecute.
3.3.2Schedules
Schedulersareofthreetypes.
1.LongTermScheduler
2.ShortTermScheduler
3.MediumTermScheduler
3.2.2.1LongTermScheduler
Itisalsocalledjobscheduler.Longtermschedulerdetermineswhich
programsareadmittedtothesystemforprocessing.Jobschedulerselects
processesfromthequeueandloadsthemintomemoryforexecution.
ProcessloadsintothememoryforCPUscheduler.Theprimaryobjectiveof
thejobscheduleristoprovideabalancedmixofjobs,suchasI/Oboundand
processorbound.Italsocontrolsthedegreeofmultiprogramming.Ifthe
degreeofmultiprogrammingisstable,thentheaveragerateofprocess
creationmustbeequaltotheaveragedeparturerateofprocessesleavingthe
system.
Onsamesystems,thelongtermschedulermaybeabsentorminimal.
Timesharing
operatingsystemshavenolongtermscheduler.Whenprocess
changesthestatefromnewtoready,thenthereisalongtermscheduler.
3.2.2.2ShortTermScheduler
ItisalsocalledCPUscheduler.Mainobjectiveisincreasingsystem
performanceinaccordancewiththechosensetofcriteria.Itisthechangeof
readystatetorunningstateoftheprocess.CPUschedulerselectsfrom
amongtheprocessesthatarereadytoexecuteandallocatestheCPUtoone
ofthem.
Shorttermscheduleralsoknownasdispatcher,executemostfrequentlyand
makesthefinegraineddecisionofwhichprocesstoexecutenext.Shortterm
schedulerisfasterthanlongternscheduler.
3.2.2.3MediumTermScheduler
Mediumtermschedulingispartoftheswappingfunction.Itremovesthe
processesfromthememory.Itreducesthedegreeofmultiprogramming.The
mediumtermschedulerisinchargeofhandlingtheswappedoutprocesses.
MediumtermschedulerisshownintheFig.3.4
Fig3.4Queueingdiagramwithmediumtermscheduler
RunningprocessmaybecomesuspendedbymakinganI/Orequest.
Suspendedprocessescannotmakeanyprogresstowardscompletion.Inthis
condition,toremovetheprocessfrommemoryandmakespaceforother
process.
Suspendedprocessismovetothesecondarystorageiscalledswapping,andthe
processissaidtobeswappedoutorrolledout.Swappingmaybenecessaryto
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

13/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

improvetheprocessmix.
3.2.2.4ComparisonbetweenScheduler
Sr.
No.
LongTermShortTermMediumTerm
1ItisjobschedulerItisCPUSchedulerItisswapping
2Speedislessthanshort
termscheduler
SpeedisveryfastSpeedisinbetweenboth
3Itcontrolsdegreeof
multiprogramming
Lesscontrolover
degreeof
multiprogramming
Reducethedegreeof
multiprogramming.
4Absentorminimalin
timesharingsystem.
Minimalintime
sharingsystem.
Timesharingsystemuse
mediumtermscheduler.
5Itselectprocessesfrom
poolandloadtheminto
memoryforexecution.
Itselectfromamong
theprocessesthatare
readytoexecute.
Processcanbe
reintroducedinto
memoryandits
executioncanbe
continued.
6Processstateis(Newto
Ready)
Processstateis(Ready
toRunning)

7Selectagoodprocess,
mixofI/Oboundand
CPUbound.
Selectanewprocess
foraCPUquite
frequently.

3.4ContextSwitch
WhentheschedulerswitchestheCPUfromexecutingoneprocessto
executinganother,thecontextswitchersavesthecontentofallprocessor
registersfortheprocessbeingremovedfromtheCPUinitsprocessbeing
removedfromtheCPUinitsprocessdescriptor.Thecontextofaprocessis
representedintheprocesscontrolblockofaprocess.Contextswitchtimeis
pureoverhead.Contextswitchingcansignificantlyaffectperformance,since
moderncomputershavealotofgeneralandstatusregisterstobesaved.
Contentswitchtimesarehighlydependentonhardwaresupport.Context
switchrequires(n+m)bXKtimeunitstosavethestateoftheprocessor
withngeneralregisters,assumingbstoreoperationsarerequiredtosave
registerandeachstoreinstructionrequiresKtimeunits.Somehardware
systemsemploytwoormoresetsofprocessorregisterstoreducetheamount
ofcontextswitchingtime.
Whentheprocessisswitchedtheinformationstoredis:
1.ProgramCounter
2.SchedulingInformation
3.Baseandlimitregistervalue
4.Currentlyusedregister
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

14/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

5.ChangedState
6.I/OState
7.Accounting

3.5OperationonProcesses
Severaloperationsarepossibleontheprocess.Processmustbecreatedand
deleteddynamically.Operatingsystemmustprovidetheenvironmentforthe
processoperation.Wediscussthetwomainoperationsonprocesses.
1.Createaprocess
2.Terminateaprocess
3.5.1CreateProcess
Operatingsystemcreatesanewprocesswiththespecifiedordefault
attributesandidentifier.Aprocessmaycreateseveralnewsubprocesses.
Syntaxforcreatingnewprocessis:
CREATE(processed,attributes)
Twonamesareusedintheprocesstheyareparentprocessandchildprocess.
Parentprocessisacreatingprocess.Childprocessiscreatedbytheparent
process.Childprocessmaycreateanothersubprocess.Soitformsatreeof
processes.WhenoperatingsystemissuesaCREATEsystemcall,itobtainsa
newprocesscontrolblockfromthepooloffreememory,fillsthefieldswith
providedanddefaultparameters,andinsertthePCBintothereadylist.Thusit
makesthespecifiedprocesseligibletoruntheprocess.
Whenaprocessiscreated,itrequiressomeparameters.Thesearepriority,
levelofprivilege,requirementofmemory,accessright,memoryprotection
informationetc.Processwillneedcertainresources,suchasCPUtime,
memory,filesandI/Odevicestocompletetheoperation.Whenprocess
createsasubprocess,thatsubprocessmayobtainitsresourcesdirectlyfrom
theoperatingsystem.Otherwiseitusestheresourcesofparentprocess.
Whenaprocesscreatesanewprocess,twopossibilitiesexistintermsof
execution.
1.Theparentcontinuestoexecuteconcurrentlywithitschildren.
2.Theparentwaitsuntilsomeorallofitschildrenhaveterminated.
Foraddressspace,twopossibilitiesoccur:
1.Thechildprocessisaduplicateoftheparentprocess.
2.Thechildprocesshasaprogramloadedintoit.
3.5.2TerminateaProcess
DELETEsystemcallisusedforterminatingaprocess.Aprocessmaydelete
itselforbyanotherprocess.Aprocesscancausetheterminationofanother
processviaanappropriatesystemcall.Theoperatingsystemreactsby
reclaimingallresourcesallocatedtothespecifiedprocess,closingfiles
openedbyorfortheprocess.PCBisalsoremovedfromitsplaceof
residenceinthelistandisreturnedtothefreepool.TheDELETEserviceis
normallyinvokedasapartoforderlyprogramtermination.
Followingaretheresourcesforterminatingthechildprocessbyparent
process.
1.Thetaskgiventothechildisnolongerrequired.
2.Childhasexceededitsusageofsomeoftheresourcesthatithasbeen
allocated.
3.Operatingsystemdoesnotallowachildtocontinueifitsparentterminates.

3.6CooperatingProcesses
Cooperatingprocessisaprocessthatcanaffectorbeaffectedbytheother
processeswhileexecuting.Ifsupposeanyprocessissharingdatawithother
processes,thenitiscalledcooperatingprocess.Benefitofthecooperating
processesare:
1.Sharingofinformation
2.Increasescomputationspeed
3.Modularity
4.Convenience
Cooperatingprocessessharetheinformation:Suchasafile,memoryetc.
Systemmustprovideanenvironmenttoallowconcurrentaccesstothese
typesofresources.Computationspeedwillincreaseifthecomputerhas
multipleprocessingelementsareconnectedtogether.Systemisconstructed
inamodularfashion.Systemfunctionisdividedintonumberofmodules.
Process1
Printf("abc")
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

15/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Process2
Printf("CBA")
CBAabcabCcBAabcCBA

Behaviorofcooperatingprocessesisnondeterministici.e.itdependson
relativeexecutionsequenceandcannotbepredictedapriori.Cooperating
processesarealsoReproducible.Forexample,supposeoneprocesswrites
ABC,anotherwritesCBAcangetdifferentoutputs,cannottellwhat
comesfromwhich.WhichprocessoutputfirstCinABCCBA.The
subtlestatesharingthatoccurshereviatheterminal.Notjustanythingcan
happen,though.Forexample,AABBCCcannotoccur.

3.7Summary
Aprocessisaprograminexecution.Asaprocessexecutes,itchangesstate.
Thestateofaprocessisdefinedbythatprocess'scurrentactivity.Eachprocess
maybeinoneofthefollowingstates:new,ready,running,waiting,or
terminated.
Eachprocessisrepresentedintheoperatingsystembyitsownprocesscontrol
block(PCB).
Aprocess,whenitisnotexecuting,placedinsomewaitingqueue.Thereare
twomajorclassesofqueuesinanoperatingsystem:I/Orequestqueuesandthe
readyqueue.Thereadyqueuecontainsalltheprocessesthatarereadyto
execute
andarewaitingfortheCPU.EachprocessisrepresentedbyaPCBandthe
PCBs
canbelinkedtogethertoformareadyqueue.Longterm(job)schedulingisthe
selectionofprocessesthatwillbeallowedtocontendfortheCPU.Normally,
longterm
schedulingisheavilyinfluencedbyresourcesallocationconsiderations,
especiallymemorymanagement.Shortterm(CPU)schedulingistheselectionof
oneprocessfromthereadyqueue.
Operatingsystemsmustprovideamechanismforparentprocessestocreate
newchildprocesses.Theparentmaywaitforitschildrentoterminatebefore
proceeding,ortheparentandchildrenmayexecuteconcurrently.Thereare
several
reasonsforallowingconcurrentexecution:informationsharingcomputation
speedup,modularity,andconvenience.
Theprocessesexecutingintheoperatingsystemmaybeeitherindependent
processesorcooperatingprocesses.Cooperatingprocessesrequireaninter
process
communicationmechanismtocommunicatewitheachother.Principally,
communicationisachievedthroughtwoschemes:sharedmemoryandmessage
passing.Thesharedmemorymethodrequirescommunicatingprocessesthrough
theuseofthesesharedvariables.Inasharedmemorysystem,theresponsibility
for
providingcommunicationrestswiththeapplicationprogrammers:theoperating
systemneedstoprovideonlythesharedmemory.Theresponsibilityfor
providing
communicationmayrestwiththeoperatingsystemitself.Thesetwoschemes
are
notmutuallyexclusiveandcanbeusedsimultaneouslywithinasingleoperating
system.

3.8ModelQuestion
Q.1Defineprocessandprograms?
Q.2DescribeProcessControlBlock?
Q.3ExplainSchedulingQueues?
Q.4Explainschedulersanditstypes?
Q.5Differentiatevarioustypesofscheduler?
Q.6Explaincontextswitch?
Q.7Explainoperationonprocesses?

CHAPTER4
THREADMANAGEMENT
UnitStructure
4.0Objectives
4.1IntroductionOfThread
4.2TypesofThread
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

16/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

4.2.1UserLevelThread
4.2.2KernelLevelThread
4.2.3AdvantageofThread
4.3MultithreadingModels
4.3.1ManytoManyModel
4.3.2ManytoOneModel
4.3.3OnetoOneModel
4.4DifferencebetweenUserLevelandKernelLevelThread
4.5DifferencebetweenProcessandThread
4.6ThreadingIssues
4.7Summary
4.8ModelQuestion

4.0Objectives
Aftergoingthroughthisunit,youwillbeableto:
TointroduceThread&itstypes,MultithreadingModelsandThreading
issues.

4.1IntroductionofThread
Athreadisaflowofexecutionthroughtheprocesscode,withitsown
programcounter,systemregistersandstack.Threadsareapopularwayto
improveapplicationperformancethroughparallelism.Athreadissometimes
calledalightweightprocess.
Threadsrepresentasoftwareapproachtoimprovingperformanceof
operatingsystembyreducingtheoverheadthreadisequivalenttoa
classicalprocess.Eachthreadbelongstoexactlyoneprocessandnothread
canexistoutsideaprocess.Eachthreadrepresentsaseparateflowof
control.
Fig.4.1showsthesingleandmultithreadedprocess.
Threadshavebeensuccessfullyusedinimplementingnetworkservers.They
alsoprovideasuitablefoundationforparallelexecutionofapplicationson
sharedmemorymultiprocessors.

4.2TypesofThread
Threadsisimplementedintwoways:
1.UserLevel
2.KernelLevel
4.2.1UserLevelThread
Inauserthread,alloftheworkofthreadmanagementisdonebythe
applicationandthekernelisnotawareoftheexistenceofthreads.The
threadlibrarycontainscodeforcreatinganddestroyingthreads,forpassing
messageanddatabetweenthreads,forschedulingthreadexecutionandfor
savingandrestoringthreadcontexts.Theapplicationbeginswithasingle
threadandbeginsrunninginthatthread.
Fig.4.2showstheuserlevelthread.
Userlevelthreadsaregenerallyfasttocreateandmanage.
AdvantageofuserlevelthreadoverKernellevelthread:
1.ThreadswitchingdoesnotrequireKernelmodeprivileges.
2.Userlevelthreadcanrunonanyoperatingsystem.
3.Schedulingcanbeapplicationspecific.
4.Userlevelthreadsarefasttocreateandmanage.
P

UserLevel
Thread
User
Space
KernelSpace
Thread
Library
Disadvantagesofuserlevelthread:
1.Inatypicaloperatingsystem,mostsystemcallsareblocking.
2.Multithreadedapplicationcannottakeadvantageofmultiprocessing.

4.2.2KernelLevelThreads
InKernellevelthread,threadmanagementdonebytheKernel.Thereisno
threadmanagementcodeintheapplicationarea.Kernelthreadsare
supporteddirectlybytheoperatingsystem.Anyapplicationcanbe
programmedtobemultithreaded.Allofthethreadswithinanapplicationare
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

17/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

supportedwithinasingleprocess.TheKernelmaintainscontextinformation
fortheprocessasawholeandforindividualsthreadswithintheprocess.
SchedulingbytheKernelisdoneonathreadbasis.TheKernelperforms
threadcreation,schedulingandmanagementinKernelspace.Kernelthreads
aregenerallyslowertocreateandmanagethantheuserthreads.
AdvantagesofKernellevelthread:
1.Kernelcansimultaneouslyschedulemultiplethreadsfromthesameprocess
onmultipleprocess.
2.Ifonethreadinaprocessisblocked,theKernelcanscheduleanotherthread
ofthesameprocess.
3.Kernelroutinesthemselvescanmultithreaded.
Disadvantages:
1.Kernelthreadsaregenerallyslowertocreateandmanagethantheuser
threads.
2.Transferofcontrolfromonethreadtoanotherwithinsameprocessrequires
amodeswitchtotheKernel.

4.2.3AdvantagesofThread
1.Threadminimizecontextswitchingtime.
2.Useofthreadsprovidesconcurrencywithinaprocess.
3.Efficientcommunication.
4.EconomyItismoreeconomicaltocreateandcontextswitchthreads.
5.Utilizationofmultiprocessorarchitectures
Thebenefitsofmultithreadingcanbegreatlyincreasedinamultiprocessor
architecture.

4.3MultithreadingModels
SomeoperatingsystemprovideacombineduserlevelthreadandKernel
levelthreadfacility.Solarisisagoodexampleofthiscombinedapproach.In
acombinedsystem,multiplethreadswithinthesameapplicationcanrunin
parallelonmultipleprocessorsandablockingsystemcallneednotblockthe
entireprocess.
Multithreadingmodelsarethreetypes:
1.Manytomanyrelationship.
2.Manytoonerelationship.
3.Onetoonerelationship.

4.3.1ManytoManyModel
Inthismodel,manyuserlevelthreadsmultiplexestotheKernelthreadof
smallerorequalnumbers.ThenumberofKernelthreadsmaybespecificto
eitheraparticularapplicationoraparticularmachine.
Fig.4.3showsthemanytomanymodel.Inthismodel,developerscan
createasmanyuserthreadsasnecessaryandthecorrespondingKernel
threadscanruninparallelsonamultiprocessor.

4.3.2ManytoOneModel
ManytoonemodelmapsmanyuserlevelthreadstooneKernellevelthread.
Threadmanagementisdoneinuserspace.Whenthreadmakesablocking
systemcall,theentireprocesswillbeblocks.Onlyonethreadcanaccessthe
Kernelatatime,somultiplethreadsareunabletoruninparallelon
multiprocessors.
Fig.4.4showsthemanytoonemodel.
K

UserLevel
Thread
Kernel
Thread
K
K

Iftheuserlevelthreadlibrariesareimplementedintheoperatingsystem,
thatsystemdoesnotsupportKernelthreadsusethemanytoonerelationship
modes.

4.3.3OnetoOneModel
Thereisonetoonerelationshipofuserlevelthreadtothekernellevel
thread.Fig.4.5showsonetoonerelationshipmodel.Thismodelprovides
moreconcurrencythanthemanytoonemodel.
K

UserLevel
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

18/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Thread
Kernel
Thread
KK
K

UserLevel
Thread
Kernel
Thread
Italsoanotherthreadtorunwhenathreadmakesablockingsystemcall.It
supportmultiplethreadtoexecuteinparallelonmicroprocessors.
Disadvantageofthismodelisthatcreatinguserthreadrequiresthe
correspondingKernelthread.OS/2,windowsNTandwindows2000useone
toonerelationshipmodel.

4.4DifferencebetweenUserLevel&KernelLevelThread
Sr.
No
UserLevelThreadsKernelLevelThread
1Userlevelthreadarefastertocreate
andmanage.
Kernellevelthreadareslowerto
createandmanage.
2Implementedbyathreadlibraryat
theuserlevel.
Operatingsystemsupportdirectlyto
Kernelthreads.
3Userlevelthreadcanrunonany
operatingsystem.
Kernellevelthreadsarespecificto
theoperatingsystem.
4Supportprovidedattheuserlevel
calleduserlevelthread.
Supportmaybeprovidedbykernel
iscalledKernellevelthreads.
5Multithreadapplicationcannottake
advantageofmultiprocessing.
Kernelroutinesthemselvescanbe
multithreaded.

4.5DifferencebetweenProcessandThread
Sr.
No
ProcessThread
1Processiscalledheavyweightprocess.Threadiscalledlightweight
process.
2Processswitchingneedsinterfacewith
operatingsystem.
Threadswitchingdoesnotneed
tocallaoperatingsystemand
causeaninterrupttotheKernel.
3Inmultipleprocessimplementationeach
processexecutesthesamecodebuthasits
ownmemoryandfileresources.
Allthreadscansharesamesetof
openfiles,childprocesses.
4Ifoneserverprocessisblockednoother
serverprocesscanexecuteuntilthefirst
processunblocked.
Whileoneserverthreadis
blockedandwaiting,second
threadinthesametaskcould
run.
5Multipleredundantprocessusesmore
resourcesthanmultiplethreaded.
Multiplethreadedprocessuses
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

19/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

fewerresourcesthanmultiple
redundantprocess.
6Inmultipleprocesseachprocessoperates
independentlyoftheothers.
Onethreadcanread,writeor
evencompletelywipeout
anotherthreadsstack.

4.6ThreadingIssues
Systemcallsforkandexecisdiscussedhere.Inamultithreadedprogram
environment,forkandexecsystemcallsischanged.Unixsystemhavetwo
versionofforksystemcalls.Onecallduplicatesallthreadsandanotherthat
duplicatesonlythethreadthatinvoketheforksystemcall.Whethertouse
oneortwoversionofforksystemcalltotallydependsupontheapplication.
Duplicatingallthreadsisunnecessary,ifexeciscalledimmediatelyafter
forksystemcall.
Threadcancellationisaprocessofthreadterminatesbeforeitscompletionof
task.Forexample,inmultiplethreadenvironment,threadconcurrently
searchingthroughadatabase.Ifanyonethreadreturnstheresult,the
remainingthreadmightbecancelled.
Threadcancellationisoftwotypes.
1.Asynchronouscancellation
2.Synchronouscancellation
Inasynchronouscancellation,onethreadimmediatelyterminatesthetarget
thread.Deferredcancellationperiodicallycheckforterminatebytarget
thread.Italsoallowthetargetthreadtoterminateitselfinanorderlyfashion.
Someresourcesareallocatedtothethread.Ifwecancelthethread,which
updatethedatawithotherthread.Thisproblemmayfacebyasynchronous
cancellationsystemwideresourcearenotfreeifthreadscancelled
asynchronously.Mostoftheoperatingsystemallowaprocessorthreadto
becancelledasynchronously.

4.7Summary
Athreadisaflowofcontrolwithinaprocess.Amultithreadedprocesscontains
severaldifferentflowsofcontrolwithinthesameaddressspace.Thebenefitsof
multithreadingincludeincreasedresponsivenesstotheuser,resourcesharing
withintheprocess,economy,andscalabilityissuessuchasmoreefficientuseof
multiplecore.
Userlevelthreadsarethreadsarevisibletotheprogrammerandare
unknowntothekernel.Theoperatingsystemkernelsupportsandmanages
kernel
levelthreads.Ingeneral,userlevelthreadsarefastertocreateandmanagethan
are
kernelthreads,asnointerventionfromthekernelisrequired.Threedifferent
types
ofmodelsrelateuserandkernelthreads:themanytoonemodelmapsmany
user
threadstoasinglethread.Theonetoonemodelmapseachuserthreadtoa
correspondingkernelthread.Themanytomanymodelmultiplexersmanyuser
threadstoasmallerorequalnumberofkernelthreads.

4.8ModelQuestion
Q.1Definethreadanditstypesindetail?
Q.2Differentiateuserlevelthreadandkernellevelthread?
Q.3ExplainvariousMultithreadedModel?
Q.4Differentiateprocessandthread?

CHAPTER5
CONCURRENCYCONTROL
UnitStructure
5.0Objectives
5.1PrincipalofConcurrency
5.2RaceCondition
5.3MutualExclusionRequirements
5.4MutualExclusionSoftwareSupport
5.5MutualExclusionHardwareSupport
5.6Semaphores
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

20/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

5.7Monitors
5.8Summary
5.9ModelQuestion

5.0Objectives
Aftergoingthroughthisunit,youwillbeableto:
TointroducetheconcurrencycontrolandRacecondition,criticalsection
problem,wheresolutionscanbeusedtoensuretheconsistencyofshared
data.
Topresentbothsoftwareandhardwaresolutionsofthecriticalsection
problem.

5.1PrincipleofConcurrency
Inasingleprocessormultiprogrammingsystem,processesareinterleavedin
timetoyieldtheappearanceofsimultaneousexecution.Evenparallelprocessing
is
notachieved,andeverthoughthereisacertainamountofoverheadinvolvedin
switchingbackandforthbetweenprocesses,interleavedexecutionprovides
major
benefitsinprocessingefficiencyandinprogramstructuring.Inamultiple
processorsystem,itispossiblenotonlytointerleavetheexecutionofmultiple
processesbutalsotooverlapthem.Itisassumed,itmayseemthatinterleaving
and
overlappingrepresentfundamentallydifferentmodesofexecutionandpresent
differentproblems.Infact,bothtechniquescanbeviewedasexamplesof
concurrentprocessing,andbothpresentthesameproblems.Therelativespeed
of
executionofprocessesItdependsonactivitiesofotherprocesses,thewayin
which
theoperatingsystemhandlesinterrupts,andtheschedulingpoliciesofthe
operating,system.
Therearequitedifficulties:
1.Thesharingofglobalresources.Forexample,iftwoprocessesbothmakeuse
of
thesameglobalvariableandbothperformreadsandwritesonthatvariable,then
theorderinwhichthevariousreadsandwritesareexecutediscritical.
2.Itisdifficultfortheoperatingsystemtomanagetheallocationofresources
optimally.
3.Itisverydifficulttolocateaprogrammingerrorbecauseresultsaretypically
not
deterministicandreproducible.
Eg:
Voidecho()
{
chin=getchar()
chout=chin
putchar(chout)
}
Thisprocedureshowstheessentialelementsofaprogramthatwillprovidea
characterechoprocedureinputisobtainedfromakeyboardonekeystrokeata
time.Eachinputcharacterisstoredinvariablechin.Itisthentransferredto
variablechoutandsenttothedisplay.Anyprogramcancallthisprocedure
repeatedlytoacceptuserinputanddisplayitontheuser'sscreen.
Inasingleprocessormultiprogrammingsystemsupportingasingleuser.
Theusercanjumpfromoneapplicationtoanother,andeach.applicationuses
the
samekeyboardforinputandthesamescreenforoutput.Becauseeach
application
needstousetheprocedureecho,itmakessenseforittobeasharedprocedure
that
isloadedintoaportionofmemoryglobaltoallapplications.Thus,onlyasingle
copyoftheechoprocedureisused,savingspace.
Thesharingofmainmemoryamongprocessesisusefultopermitefficient
andcloseinteractionamongprocessesConsiderthefollowingsequence:
1.ProcessP1invokestheechoprocedureandisinterruptedimmediatelyafter
getcharreturnsitsvalueandstoresitinchin.Atthispoint,themostrecently
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

21/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

enteredcharacter,x,isstoredinvariablechin.
2.ProcessP2isactivatedandinvokestheechoprocedure,whichrunsto
conclusion,inputtingandthendisplayingasinglecharacter,y,onthescreen.
3.ProcessP1isresumed.Bythistime,thevaluexhasbeenoverwritteninchin
andthereforelost.Instead,chincontainsy,whichistransferredtochoutand
displayed.
Thus,thefirstcharacterislostandthesecondcharacterisdisplayedtwice.
Becauseofsharedglobalvariable,chin.Ifoneprocessupdatestheglobal
variable
andthenisinterrupted,another.processmayalterthevariablebeforethefirst
processcanuseitsvalue.However,ifonlyoneprocessatatimemaybeinthat
procedure.Thentheforegoingsequencewouldresultinthefollowing:
1.ProcessP1invokestheechoprocedureandisinterruptedimmediatelyafter
the
conclusionoftheinputfunction.Atthispoint,themostrecentlyentered
character,
x,isstoredinvariablechin.
2.ProcessP2isactivatedandinvokestheechoprocedure.However,becauseP1
is
stillinsidetheechoprocedure,althoughcurrentlysuspended,P2isblockedfrom
enteringtheprocedure.Therefore,P2issuspendedawaitingtheavailabilityof
the
echoprocedure.
3.Atsomelatertime,processPIisresumedandcompletesexecutionofecho.
The
propercharacter,x,isdisplayed.
4.WhenPIexits'echo,thisremovestheblockonP2.WhenP2islaterresumed,
theechoprocedureissuccessfullyinvoked.
Thereforeitisnecessarytoprotectsharedglobalvariables.Andthattheonly
waytodothatistocontrolthecodethataccessesthevariable.

5.2RaceCondition
Araceconditionoccurswhenmultipleprocessesorthreadsreadandwrite
dataitemssothatthefinalresultdependsontheorderofexecutionof
instructions
inthemultipleprocesses.
Supposethattwoprocesses,P1andP2,sharetheglobalvariablea.Atsome
pointinitsexecution,P1updatesatothevalue1,andatsomepointinits
execution,P2updatesatothevalue2.Thus,thetwotasksareinaracetowrite
variablea.Inthisexamplethe"loser"oftherace(theprocessthatupdateslast)
determinesthefinalvalueofa.
ThereforeOperatingSystemConcernsoffollowingthings
1.Theoperatingsystemmustbeabletokeeptrackofthevariousprocesses
2.Theoperatingsystemmustallocateanddeallocatevariousresourcesforeach
activeprocess.
3.Theoperatingsystemmustprotectthedataandphysicalresourcesofeach
processagainstunintendedinterferencebyotherprocesses.
4.Thefunctioningofaprocess,andtheoutputitproduces,mustbeindependent
of
thespeedatwhichitsexecutioniscarriedoutrelativetothespeedofother
concurrentprocesses.
ProcessInteractioncanbedefinedas
Processesunawareofeachother
Processesindirectlyawareofeachother
Processesdirectlyawareofeachother
Concurrentprocessescomeintoconflictwitheachotherwhentheyare
competingfortheuseofthesameresource.
Twoormoreprocessesneedtoaccessaresourceduringthecourseoftheir
execution.Eachprocessisunawareoftheexistenceoftheotherprocesses.
Thereis
noexchangeofinformationbetweenthecompetingprocesses.

5.3RequirementsforMutualExclusion
1.Mutualexclusionmustbeenforced:Onlyoneprocessatatimeisallowedinto
itscriticalsection,amongallprocessesthathavecriticalsectionsforthesame
resourceorsharedobject.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

22/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

2.Aprocessthathaltsinitsnoncriticalsectionmustdosowithoutinterfering
with
otherprocesses.
3.Itmustnotbepossibleforaprocessrequiringaccesstoacriticalsectiontobe
delayedindefinitely:nodeadlockorstarvation.
4.Whennoprocessisinacriticalsection,anyprocessthatrequestsentrytoits
criticalsectionmustbepermittedtoenterwithoutdelay.
5.Noassumptionsaremadeaboutrelativeprocessspeedsornumberof
processors.
6.Aprocessremainsinsideitscriticalsectionforafinitetimeonly.

5.4MutualExclusionSoftwareSupport
Softwareapproachescanbeimplementedforconcurrentprocessesthat
executesonasingleprocessororamultiprocessormachinewithsharedmain
memory.
5.4.1DekkersAlgorithm
Dekkersalgorithmisfortwoprocessesbasedsolelyonsoftware.Eachof
theseprocessesloopindefinitely,repeatedlyenteringandreenteringits
criticalsection.Aprocess(P0&P1)thatwishestoexecuteitscritical
sectionfirstenterstheiglooandexaminestheblackboard.Theprocess
numberiswrittenontheblackboard,thatprocessleavestheiglooand
proceedstocriticalsection.Otherwisethatprocesswillwaitforitsturn.
Processreentersintheiglootochecktheblackboard.Itrepeatsthisexercise
untilitisallowedtoenteritscriticalsection.Thisprocedureisknownas
busywaiting.
Informalterms,thereisasharedglobalvariable:Varturn:0:1
Process0

Whileturn#0do(nothing)
<criticalsection>
turn:=1

Process1

Whileturn#1do(nothing)
<criticalsection>
Turn:=0

Theabovesolutionsatisfythepropertyofmutualexclusion.Drawbackofthesolutionare
asfollows:
1.Processesmuststrictlyalternateintheiruseoftheircriticalsection.
2.ifoneprocessfails,theotherprocessispermanentlyblocked.

Drawbacksofsoftwaresolutions
1.Complicatedtoprogram.
2.busywaitingispossible.
3.itwouldbemoreefficienttoblockprocessesthatarewaiting.
4.makesdifficultassumptionsaboutthememorysystem.

5.5MutualExclusionHardwareSupport
Hardwareapproachestomutualexclusion.
5.5.1InterruptDisabling:
Inauniprocessormachine,concurrentprocessescannotbeoverlappedthey
canonlybeinterleaved.Furthermore,aprocesswillcontinuetorununtilit
invokes
anoperatingsystemserviceoruntilitisinterrupted.Therefore,toguarantee
mutualexclusion,itissufficienttopreventaprocessfrombeinginterrupted.
This
capabilitycanbeprovidedintheformofprimitivesdefinedbythesystemkernel
fordisablingandenablinginterrupts.
eg:
while(true)
(
disableinterrupts()
criticalsection
enableinterrupts()
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

23/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

)remainder
Becausethecriticalsectioncannotbeinterrupted,mutualexclusionis
guaranteed.
Disadvantages
Itworksonlyinasingleprocessorenvironment.
Interruptscanbelostifnotservicedpromptly.
Aprocesswaitingtoenteritscriticalsectioncouldsufferfromstarvation.
5.5.2TestandSetInstruction
Itisspecialmachineinstructionusedtoavoidmutualexclusion.Thetestand
setinstructioncanbedefinedasfollows:
booleantestset(inti)
{
if(i==o)
{
i=1
returntrue
}
else.,.
{
returnfalse
}
Theabovefunctioniscarriedoutautomatically.
Advantages
1.Itissimpleandeasytoverify.
2.itisapplicabletoanynumberofprocesses.
3.itcanbusedtosupportmultiplecriticalsection.
Disadvantages
1.Busywaitingispossible.
2.Starvationisalsopossible.
3.Theremaybedeadlock.

5.6Semaphores
Thesolutionsofthecriticalsectionproblemrepresentedinthesectionisnot
easytogeneralizetomorecomplexproblems.Toovercomethisdifficulty,
wecanuseasynchronizationtoolcallasemaphore.AsemaphoreSisan
integervariablethat,apartfrominitialization,isaaccessedtwostandard
atomicoperations:waitandsignal.ThisoperationswereoriginallytermedP
(forwaitfromtheDutchproberen,totest)andV(forsignalfrom
verhogen,toincrement).
TheClassicaldefinitionofwaitandsignalare
Wait(S)
{
while(S<=0)
S=S1
}
signal(S)
{
S=S+1
}
Theintegervalueofthesemaphoreinthewaitandsignaloperationsmustbe
executedindivisibly.Thatis,whenoneprocessmodifiesthesemaphore
value,nootherprocesscansimultaneouslymodifythatsamesemaphore
value.
Inaddition,inthecaseofthewait(S),thetestingoftheintegervalueofS(S
0),anditspossiblemodification(S:=S1),mustalsobeexecutedwithout
interruption.
Semaphoresarenotprovidedbyhardware.Buttheyhaveseveralattractive
properties:
1.Semaphoresaremachineindependent.
2.Semaphoresaresimpletoimplement.
3.Correctnessiseasytodetermine.
4.Canhavemanydifferentcriticalsectionswithdifferentsemaphores.
5.Semaphoreacquiremanyresourcessimultaneously.
DrawbackofSemaphore
1.Theyareessentiallysharedglobalvariables.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

24/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

2.Accesstosemaphorescancomefromanywhereinaprogram.
3.Thereisnocontrolorguaranteeofproperusage.
4.Thereisnolinguisticconnectionbetweenthesemaphoreandthedatato
which
thesemaphorecontrolsaccess.
5.Theyservetwopurposes,mutualexclusionandschedulingconstraints.

5.7Monitors
Themonitorisaprogramminglanguageconstructthatprovidesequivalent
functionalitytothatofsemaphoresandthatiseasiertocontrol.Themonitor
constructhasbeenimplementedinanumberofprogramminglanguages,
includingConcurrentPascal,PascalPlus,Modula2,Modula3,andJava.It
hasalsobeenimplementedasaprogramlibrary.Thisallowsprogrammers
toputmonitorlocksonanyobject.
MonitorwithSignal
Amonitorisasoftwaremoduleconsistingofoneormoreprocedures,an
initializationsequence,andlocaldataThecharacteristicsofamonitorare
thefollowing:
1.Thelocaldatavariablesareaccessibleonlybythemonitor'sproceduresand
not
byanyexternalprocedure.
2.Aprocessentersthemonitorbyinvokingoneofitsprocedures.
3.OnlyoneprocessmayDeexecutinginthemonitoratatimeanyother
process
thathasinvokedthemonitorisblocked,waitingforthemonitortobecome
available.
Amonitorsupportssynchronizationbytheuseofconditionvariablesthat
arecontainedWithinthemonitorandaccessibleonlywithinthemonitor.
Conditionvariablesareaspecialdatatypeinmonitors,whichareoperatedonby
twofunctions:
cwait(c):Suspendexecutionofthecallingprocessonconditionc.Themonitor
is
nowavailableforusebyanotherprocess.
csignal(c):Resumeexecutionofsomeprocessblockedafteracwaitonthe
same
condition)lfthereareseveralsuchprocesses,chooseoneofthemifthereisno
suchprocess,donothing.
Monitorwaitandsignaloperationsaredifferentfromthoseforthe
semaphore.Ifaprocessinamonitorsignalsandnotaskiswaitingonthe
conditionvariable,thesignalislost.
Althoughaprocesscanenterthemonitorbyinvokinganyofitsprocedures,
wecanthinkofthemonitorashavingasingleentrypointthatisguardedso
thatonlyoneprocessmaybeinthemonitoratatime.Otherprocessesthat
attempttoenterthemonitorjoinaqueueofprocessesblockedwaitingfor
monitoravailability.
Onceaprocessisinthemonitor,itmaytemporarilyblockitselfoncondition
xbyissuingcwait(x)itisthenplacedinaqueueofprocesseswaitingto
reenterthemonitorwhentheconditionchanges,andresumeexecutionatthe
pointinitsprogramfollowingthecwait(x)call.
Ifaprocessthatisexecutinginthemonitordetectsachangeincondition
variablex,itissuescsignal(x),whichalertsthecorrespondingcondition
queuethattheconditionhaschanged.
Aproducercanaddcharacterstothebufferonlybymeansoftheprocedure
appendinsidethemonitortheproducerdoesnothavedirectaccessto
buffer.
Theprocedurefirstcheckstheconditionnotfulltodetermineifthereis
spaceavailableinthebuffer.Ifnot,theprocessexecutingthemonitoris
blockedonthatcondition.

5.7Summary
Criticalsectionisacodethatonlyoneprocessatatimecanbeexecuting.
Criticalsectionproblemisdesignanalgorithmthatallowsatmostoneprocess
into
thecriticalsectionatatime,withoutdeadlock.Solutionofthecriticalsection
problemmustsatisfymutualexclusion,progress,boundedwaiting.
Semaphoreisasynchronizationvariablethattasksonpositiveinteger
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

25/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

values.Binarysemaphorearethosethathaveonlytwovalues0and1.
semaphores
arenotprovidedbyhardware.Semaphoreisusedtosolvecriticalsection
problem.
Amonitorisasoftwaremoduleconsistingofoneormoreprocedures,an
initializationsequenceandlocaldata.Componentsofmonitorsareshareddata
declaration,shareddatainitialization,operationsonshareddataand
synchronizationstatement.

5.8ModelQuestion
Q.1Explaininbriefracecondition?
Q.2Definethetermcriticalsection?
Q.3Whataretherequirementforcriticalsectionproblem?
Q.4Writeashortnoteon:
a)Semaphore
b)Monitors
Q.5Whataresemaphores?Howdotheyimplementmutualexclusion?
Q.6Describehardwaresolutiontothecriticalsectionproblem?

CHAPTER6
DEADLOCK
UnitStructure
6.0Objectives
6.1Introduction
6.2DeadlockCharacterization
6.2.1ResourceAllocationGraph
6.3MethodforHandlingDeadlock
6.4DeadlockPreventionRecovery
6.5AvoidanceandProtection
6.6DeadlockDetection
6.7RecoveryfromDeadlock
6.8Summary
6.9ModelQuestion

6.0Objectives
Aftergoingthroughthisunit,youwillbeableto:
Todevelopadescriptionofdeadlocks,whichpreventsetsofconcurrent
processesfromcompletingtheirtasks.
Topresentnumberofdifferentmethodsforpreventingoravoiding
deadlocksinacomputersystem.

6.1Introduction
Inamultiprogrammingenvironment,severalprocessesmaycompetefora
finitenumberofresources.Aprocessrequestsresourcesiftheresourcesarenot
availableatthattime,theprocessentersawaitstate.Itmayhappenthatwaiting
processeswillneveragainchangestate,becausetheresourcestheyhave
requested
areheldbyotherwaitingprocesses.Thissituationiscalleddeadlock.
Ifaprocessrequestsaninstanceofaresourcetype,theallocationofany
instanceofthetypewillsatisfytherequest.Ifitwillnot,thentheinstancesare
not
identical,andtheresourcetypeclasseshavenotbeendefinedproperly.
Aprocessmustrequestaresourcebeforeusingit,andmustreleasethe
resourceafterusingit.Aprocessmayrequestasmanyresourcesasitrequiresto
carryoutitsdesignatedtask.
Underthenormalmodeofoperation,aprocessmayutilizearesourcein
onlythefollowingsequence:
1.Request:Iftherequestcannotbegrantedimmediately,thentherequesting
processmustwaituntilitcanacquiretheresource.
2.Use:Theprocesscanoperateontheresource.
3.Release:Theprocessreleasestheresource

6.2DeadlockCharacterization
Indeadlock,processesneverfinishexecutingandsystemresourcesaretied
up,preventingotherjobsfromeverstarting.
NecessaryConditions
Adeadlocksituationcanariseifthefollowingfourconditionshold
simultaneously
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

26/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

inasystem:
1.Mutualexclusion:Atleastoneresourcemustbeheldinanonsharable
mode
thatis,onlyoneprocessatatimecanusetheresource.Ifanotherprocess
requests
thatresource,therequestingprocessmustbedelayeduntiltheresourcehasbeen
released.
2.Holdandwait:Theremustexistaprocessthatisholdingatleastone
resource
andiswaitingtoacquireadditionalresourcesthatarecurrentlybeingheldby
other
processes.
3.Nopreemption:Resourcescannotbepreemptedthatis,aresourcecanbe
releasedonlyvoluntarilybytheprocessholdingit,afterthatprocess,has
completeditstask.
4.Circularwait:Theremustexistaset{P0,P1,...,Pn}ofwaitingprocesses
such
thatP0iswaitingforaresourcethatisheldbyP1,P1iswaitingforaresource
that
isheldbyP2,.,Pn1iswaitingforaresourcethatisheldbyPn,andPnis
waitingforaresourcethatisheldbyP0.
6.2.1ResourceAllocationGraph
Deadlockscanbedescribedmorepreciselyintermsofadirectedgraph
calledasystemresourceallocationgraph.ThesetofverticesVispartitioned
into
twodifferenttypesofnodesP={P1,P2,Pn}thesetconsistingofallthe
active
processesinthesystemandR={R1,R2,,R1},thesetconsistingofall
resourcetypesinthesystem.
AdirectededgefromprocessPitoresourcetypeRjisdenotedbyPiRj,it
signifiesthatprocessPirequestedaninstanceofresourcetypeRjandis
currently
waitingforthatresource.AdirectededgefromresourcetypeRjtoprocessPiis
denotedbyRj_PiitsignifiesthataninstanceofresourcetypeRjhasbeen
allocatedtoprocessPi.AdirectededgePi_Rjiscalledarequestedgea
directed
edgeRj_Piiscalledanassignmentedge.
WhenprocessPirequestsaninstanceofresourcetypeRj,arequestedgeis
insertedintheresourceallocationgraph.Whenthisrequestcanbefulfilled,the
requestedgeisinstantaneouslytransformedtoanassignmentedge.Whenthe
processnolongerneedsaccesstothe,resourceitreleasestheresource,andasa
resulttheassignmentedgeisdeleted.
Definitionofaresourceallocationgraph,itcanbeshownthat,ifthegraph
containsnocycles,thennoprocessinthesystemisdeadlocked.If,ontheother
hand,thegraphcontainsthecycle,thenadeadlockmustexist.
Ifeachresourcetypehasseveralinstances,thenacycleimpliesthata
deadlockhasoccurred.Ifthecycleinvolvesonlyasetofresourcestypes,each
of
whichhasonlyasingleinstance,thenadeadlockhasoccurred.Eachprocess
involvedinthecycleisdeadlocked.Inthiscase,acycleinthegraphisbotha
necessaryandasufficientconditionfortheexistenceofdeadlock.
AsetofverticesVandasetofedgesE.
Vispartitionedintotwotypes:
oP={P1,P2,,Pn},thesetconsistingofalltheprocessesinthe
system.
oR={R1,R2,,Rm},thesetconsistingofallresourcetypesinthe
system.
requestedgedirectededgeP1Rj
assignmentedgedirectededgeRjPi
Fig.ResourceAllocationGraph
Ifeachresourcetypehasseveralinstance,thenacycledoesnotnecessarily
implythatadeadlockincurred.Inthiscase,acycleinthegraphisanecessary
but
notasufficientconditionfortheexistenceofdeadlock.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

27/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

SupposethatprocessP3requestsaninstanceofresourcetypeR2Sinceno
resourceinstanceiscurrentlyavailable,arequestedgeP3R2isaddedtothe
graph.Atthispoint,twominimalcyclesexistinthesystem:
P1R1P2R3P3R2P1
P2R3P3R2P2
Fig.ResourceAllocationGraphwithDeadlock
ProcessesP1,P2,andP3aredeadlocked.ProcessP2iswaitingforthe
resourceR3,whichisheldbyprocessP3.ProcessP3,ontheotherhand,is
waiting
foreitherprocessP1orprocessP2toreleaseresourceR2.Inaddition,process
PIis
waitingforprocessP2toreleaseresourceR1.

_____________________________________________
_
6.3MethodForHandlingDeadlock//Detection
Therearearethreedifferentmethodsfordealingwiththedeadlockproblem:
Wecanuseaprotocoltoensurethatthesystemwillneverenteradeadlock
state.
Wecanallowthesystemtoenteradeadlockstateandthenrecover.
Wecanignoretheproblemalltogether,andpretendthatdeadlocksneveroccur
in
thesystem.Thissolutionistheoneusedbymostoperatingsystems,including
UNIX.
Deadlockavoidance,ontheotherhand,requiresthattheoperatingsystembe
giveninadvanceadditionalinformationconcerningwhichresourcesaprocess
will
requestanduseduringitslifetime.Withthisadditionalknowledge,wecan
decide
foreachrequestwhetherornottheprocessshouldwait.Eachrequestrequires
that
thesystemconsidertheresourcescurrentlyavailable,theresourcescurrently
allocatedtoeachprocess,andthefuturerequestsandreleasesofeachprocess,to
decidewhetherthecurrentrequestcanbesatisfiedormustbedelayed.
Ifasystemdoesnotemployeitheradeadlockpreventionoradeadlock
avoidancealgorithm,thenadeadlocksituationmayoccurIfasystemdoesnot
ensurethatadeadlockwillneveroccur,andalsodoesnotprovideamechanism
for
deadlockdetectionandrecovery,thenwemayarriveatasituationwherethe
systemisinadeadlockstateyethasnowayofrecognizingwhathashappened.

6.4DeadlockPrevention
Foradeadlocktooccur,eachofthefournecessaryconditionsmusthold.By
ensuringthatatleastononetheseconditionscannothold,wecanpreventthe
occurrenceofadeadlock.
6.4.1MutualExclusion
Themutualexclusionconditionmustholdfornonsharableresources.For
example,aprintercannotbesimultaneouslysharedbyseveralprocesses.
Sharable
resources,ontheotherhand,donotrequiremutuallyexclusiveaccess,andthus
cannotbeinvolvedinadeadlock.
6.4.2HoldandWait
1.Whenwheneveraprocessrequestsaresource,itdoesnotholdanyother
resources.Oneprotocolthatbeusedrequireseachprocesstorequestandbe
allocatedallitsresourcesbeforeitbeginsexecution.
2.Analternativeprotocolallowsaprocesstorequestresourcesonlywhenthe
processhasnone.Aprocessmayrequestsomeresourcesandusethem.Beforeit
canrequestanyadditionalresources,howeveritmustreleasealltheresources
that
itiscurrentlyallocatedherearetwomaindisadvantagestotheseprotocols.First,
resourceutilizationmaybelow,sincemanyoftheresourcesmaybeallocated
but
unusedforalongperiod.Intheexamplegiven,forinstance,wecanreleasethe
tapedriveanddiskfile,andthenagainrequestthediskfileandprinter,onlyif
we
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

28/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

canbesurethatourdatawillremainonthediskfile.Ifwecannotbeassured
that
theywill,thenwemustrequestallresourcesatthebeginningforbothprotocols.
Second,starvationispossible.
6.4.3NoPreemption
Ifaprocessthatisholdingsomeresourcesrequestsanotherresourcethat
cannotbeimmediatelyallocatedtoit,thenallresourcescurrentlybeingheldare
preempted.Thatisthisresourcesareimplicitlyreleased.Thepreempted
resources
areaddedtothelistofresourcesforwhichtheprocessiswaitingprocesswillbe
restartedonlywhenitcanregainitsoldresources,aswellasthenewonesthatit
is
requesting.
6.4.4CircularWait
Circularwaitconditionneverholdsistoimposeatotalorderingofall
resourcetypes,andtorequirethateachprocessrequestsresourcesinan
increasing
orderofenumeration.
LetR={R1,R2,...,Rn}bethesetofresourcetypes.Weassigntoeach
resourcetypeauniqueintegernumber,whichallowsustocomparetwo
resources
andtodeterminewhetheroneprecedesanotherinourordering.Formally,we
defineaonetoonefunctionF:R_N,whereNisthesetofnaturalnumbers.

6.5DeadlockAvoidance
Preventdeadlocksrequestscanbemade.Therestraintsensurethatatleast
oneofthenecessaryconditionsfordeadlockcannotoccur,and,hence,that
deadlockscannothold.Possiblesideeffectsofpreventingdeadlocksbythis,
melted,however,areTowdeviceutilizationandreducedsystemthroughput.
Analternativemethodforavoidingdeadlocksistorequireadditional
informationabouthowresourcesaretoberequested.Forexample,inasystem
withonetapedriveandoneprinter,wemightbetoldthatprocessPwillrequest
firstthetapedrive,andlatertheprinter,beforereleasingbothresources.Process
Q
ontheotherhand,willrequestfirsttheprinter,andthenthetapedrive.Withthis
knowledgeofthecompletesequenceofrequestsandreleasesforeachprocess
we
candecideforeachrequestwhetherornottheprocessshouldwait.
Adeadlockavoidancealgorithmdynamicallyexaminestheresourceallocation
statetoensurethattherecanneverbeacircularwaitcondition.The
resourceallocationstateisdefinedbythenumberofavailableandallocated
resources,andthemaximumdemandsoftheprocesses.
6.5.1SafeState
Astateissafeifthesystemcanallocateresourcestoeachprocess(uptoits
maximum)insomeorderandstillavoidadeadlock.Moreformally,asystemis
in
asafestateonlyifthereexistsasafesequence.Asequenceofprocesses<P1,
P2,..
Pn>isasafesequenceforthecurrentallocationstateif,foreachPithe
resources
thatPjcanstillrequestcanbesatisfiedbythecurrentlyavailableresourcesplus
the
resourcesheldbyallthePj,withj<i.Inthissituation,iftheresourcesthat
process
Pineedsarenotimmediatelyavailable,thenPicanwaituntilallPjhave
finished.
Whentheyhavefinished,Picanobtainallofitsneededresources,completeits
designatedtaskreturnitsallocatedresources,andterminate.WhenPi
terminates,
Pi+1canobtainitsneededresources,andsoon.
Fig.Safe,Unsafe&DeadlockState
Ifnosuchsequenceexists,thenthesystemstateissaidtobeunsafe.
6.5.2ResourceAllocationGraphAlgorithm
SupposethatprocessPirequestsresourceRj.Therequestcanbegranted
onlyifconvertingtherequestedgePiRjtoanassignmentedgeRjPidoes
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

29/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

notresultintheformationofacycleintheresourceallocationgraph.
6.5.3Banker'sAlgorithm
Theresourceallocationgraphalgorithmisnotapplicabletoaresourceallocation
systemwithmultipleinstancesofeachresourcetype.Thedeadlockavoidance
algorithmthatwedescribenextisapplicabletosuchasystem,butis
lessefficientthantheresourceallocationgraphscheme.Thisalgorithmis
commonlyknownasthebanker'salgorithm.

6.6DeadlockDetection
Ifasystemdoesnotemployeitheradeadlockpreventionoradeadlock
avoidance
algorithm,thenadeadlocksituationmayoccur.
Analgorithmthatexaminesthestateofthesystemtodeterminewhethera
deadlockhasoccurred.
Analgorithmtorecoverfromthedeadlock.
6.6.1SingleInstanceofEachResourceType
Ifallresourceshaveonlyasingleinstance,thenwecandefineadeadlock
detectionalgorithmthatusesavariantoftheresourceallocationgraph,calleda
waitforgraph.Weobtainthisgraphfromtheresourceallocationgraphby
removingthenodesoftyperesourceandcollapsingtheappropriateedges.
6.6.2SeveralInstancesofaResourceType
Thewaitforgraphschemeisnotapplicabletoaresourceallocationsystem
withmultipleinstancesofeachresourcetype.
Thealgorithmusedare:
Available:Avectoroflengthmindicatesthenumberofavailableresourcesof
eachtype.
Allocation:Annxmmatrixdefinesthenumberofresourcesofeachtype
currentlyallocatedtoeachprocess.
Request:Annxmmatrixindicatesthecurrentrequestofeachprocess.If
Request[i,j]=k,thenprocessP,isrequestingkmoreinstancesofresourcetype
Rj.
6.6.3DetectionAlgorithmUsage
Ifdeadlocksoccurfrequently,thenthedetectionalgorithmshouldbe
invokedfrequently.Resourcesallocatedtodeadlockedprocesseswillbeidle
until
thedeadlockcanbebroken.

6.7RecoveryfromDeadlock
Whenadetectionalgorithmdeterminesthatadeadlockexists,several
alternativesexist.Onepossibilityistoinformtheoperatorthatadeadlockhas
spurred,andtolettheoperatordealwiththedeadlockmanually.Theother
possibilityistoletthesystemrecoverfromthedeadlockautomatically.There
are
twooptionsforbreakingadeadlock.Onesolutionissimplytoabortoneormore
processestobreakthecircularwait.Thesecondoptionistopreemptsome
resourcesfromoneormoreofthedeadlockedprocesses.
6.7.1ProcessTermination
Toeliminatedeadlocksbyabortingaprocess,weuseoneoftwomethods.In
bothmethods,thesystemreclaimsallresourcesallocatedtotheterminated
processes.
Abortalldeadlockedprocesses:Thismethodclearlywillbreakthedead
lock
cycle,butatagreatexpense,sincetheseprocessesmayhavecomputedfora
long
time,andtheresultsofthesepartialcomputationsmustbediscarded,and
probably
mustberecomputed.
Abortoneprocessatatimeuntilthedeadlockcycleiseliminated:This
methodincursconsiderableoverhead,sinceaftereachprocessisaborteda
deadlockdetectionalgorithmmustbeinvokedtodeterminewhetheraprocesses
arestilldeadlocked.
6.7.2ResourcePreemption
Toeliminatedeadlocksusingresourcepreemption,wesuccessivelypreempt
someresourcesfromprocessesandgivetheseresourcestootherprocessesuntil
he
deadlockcycleisbroken.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

30/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Thethreeissuesareconsideredtorecoverfromdeadlock
1.Selectingavictim
2.Rollback
3.Starvation

6.8Summary
Adeadlockedstateoccurswhentwoormoreprocessesarewaiting
indefinitelyforaneventthatcanbecausedonlyoneofthewaitingprocesses.
Therearethreeprincipalmethodsfordealingwithdeadlocks:
Usesomeprotocoltopreventoravoiddeadlocks,enteringthatthesystem
willneverenteradeadlockedstate.
Allowthesystemtoenteradeadlockedstate,detectit,andthenrecover.
Ignoretheproblemaltogetherandpretendthatdeadlocksneveroccurinthe
system.
Deadlockpreventionisasetofmethodsforensuringthatatleastoneofthe
necessaryconditioncannothold.Deadlockavoidancerequiresadditional
informationabouthowresourcesaretoberequested.Deadlockavoidance
algorithmdynamicallyexaminestheresourceallocationstatetoensurethata
circularwaitconditioncanneverexist.Deadlockoccuronlywhensomeprocess
makesarequestthatcannotegrantedimmediately.

6.9ModelQuestion
Q.1Writeashortnoteondeadlock?
Q.2Explainthecharacteristicofdeadlock?
Q.3Describevariousmethodsfordeadlockprevention?
Q.4Explaintheresourceallocationgraph?
Q.5Writeanoteonsafestate'?
Q.6Explainhowdeadlocksaredetectedandcorrected?
Q.7Whatarethedifferencebetweenadeadlockpreventionanddeadlock
Avoidance?

CHAPTER7
MEMORYMANAGEMENT
UnitStructure
7.0Objectives
7.1Introduction
7.2MemoryPartitioning
7.3Swapping
7.4Paging
7.5Segmentation
7.6Summary
7.7ModelQuestion

7.1Objective
Toprovideadetaileddescriptionofvariouswaysoforganizingmemory
hardware.
Todiscussvariousmemorymanagementtechniques,includingpaging
andsegmentation.
ToprovideadetaileddescriptionoftheIntelPentium,whichsupports
bothpuresegmentationandsegmentationwithpaging.

7.1MemoryManagement
Memoryiscentraltotheoperationofamoderncomputersystem.Memoryis
alargearrayofwordsorbytes,eachwithitsownaddress.
Aprogramresidesonadiskasabinaryexecutablefile.Theprogrammust
bebroughtintomemoryandplacedwithinaprocessforittobeexecuted
Dependingonthememorymanagementinusetheprocessmaybemoved
between
diskandmemoryduringitsexecution.Thecollectionofprocessesonthedisk
that
arewaitingtobebroughtintomemoryforexecutionformstheinputqueue.i.e.
selectedoneoftheprocessintheinputqueueandtoloadthatprocessinto
memory.Wecanprovideprotectionbyusingtworegisters,usuallyabaseanda
limit,asshowninfig.7.1.thebaseregisterholdsthesmallestlegalphysical
memoryaddressthelimitregisterspecifiesthesizeoftherange.Forexample,if
thebaseregisterholds300040andthelimitregisteris120900,thentheprogram
canlegallyaccessalladdressesfrom300040through420939(inclusive).
Fig7.1Abaseandlimitregisterdefinealogicaladdressspace.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

31/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Thebindingofinstructionsanddatatomemoryaddressescanbedoneatany
stepalongtheway:
Compiletime:Ifitisknownatcompiletimewheretheprocesswillreside
inmemory,thenabsolutecodecanbegenerated.
Loadtime:Ifitisnotknownatcompiletimewheretheprocesswillreside
inmemory,thenthecompilermustgeneraterelocatablecode.
Executiontime:Iftheprocesscanbemovedduringitsexecutionfromone
memorysegmenttoanother,thenbindingmustbedelayeduntilruntime.
7.1.1DynamicLoading
Bettermemoryspaceutilizationcanbedonebydynamicloading.Withdynamic
loading,aroutineisnotloadeduntilitiscalled.Allroutinesarekeptondiskina
relocatableloadformat.Themainprogramisloadedintomemoryandis
executed.
Theadvantageofdynamicloadingisthatanunusedroutineisneverloaded.
7.1.2DynamicLinking
Mostoperatingsystemssupportonlystaticlinking,inwhichsystem
languagelibrariesaretreatedlikeanyotherobjectmoduleandarecombinedby
the
loaderintothebinaryprogramimage.Theconceptofdynamiclinkingissimilar
to
thatofdynamicloading.Ratherthanloadingbeingpostponeduntilexecution
time,
linkingispostponed.Thisfeatureisusuallyusedwithsystemlibraries,suchas
languagesubroutinelibraries.Withdynamiclinking,astubisincludedinthe
imageforeachlibraryroutinereference.Thisstubisasmallpieceofcodethat
indicateshowtolocatetheappropriatememoryresidentlibraryrouting.
Theentireprogramanddataofaprocessmustbeinphysicalmemoryforthe
processtoexecute.Thesizeofaprocessislimitedtothesizeofphysical
memory.
Sothataprocesscanbelargerthantheamountofmemoryallocatedtoit,a
techniquecalledoverlaysissometimesused.Theideaofoverlaysistokeepin
memoryonlythoseinstructionsanddatathatareneededatanygiventime.
When
otherinstructionsareneeded,theyareloadedintospacethatwasoccupied
previouslybyinstructionsthatarenolongerneeded.
Example,consideratwopassassembler.Duringpass1,itconstructsa
symboltablethen,duringpass2,itgeneratesmachinelanguagecode.Wemay
be
abletopartitionsuchanassemblerintopass1code,pass2code,thesymbol
table
1,andcommonsupportroutinesusedbybothpass1andpass2.
Letusconsider
Pass170K
Pass280K
Symboltable20K
Commonroutines30K
Toloadeverythingatonce,wewouldrequire200Kofmemory.Ifonly
150Kisavailable,wecannotrunourprocess.Butpass1andpass2donotneed
to
beinmemoryatthesametime.Wethusdefinetwooverlays:OverlayAisthe
symboltable,commonroutines,andpass1,andoverlayBisthesymboltable,
commonroutines,andpass2.
Weaddanoverlaydriver(10K)andstartwithoverlayAinmemory.When
wefinishpass1,wejumptotheoverlaydriver,whichreadsoverlayBinto
memory,overwritingoverlayA,andthentransferscontroltopass2.OverlayA
needsonly120K,whereasoverlayBneeds130K
Asindynamicloading,overlaysdonotrequireanyspecialsupportfromthe
operatingsystem.

7.1.3LogicalversusPhysicalAddressSpace
AnaddressgeneratedbytheCPUiscommonlyreferredtoasalogical
address,whereasanaddressseenbythememoryunitiscommonlyreferredtoas
a
physicaladdress.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

32/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Thecompiletimeandloadtimeaddressbindingschemesresultinan
environmentwherethelogicalandphysicaladdressesarethesame.The
executiontime
addressbindingschemeresultsinanenvironmentwherethelogicaland
physicaladdressesdiffer.Inthiscase,weusuallyrefertothelogicaladdressasa
virtualaddress.Thesetofalllogicaladdressesgeneratedbyaprogramis
referred
toasalogicaladdressspacethesetofallphysicaladdressescorrespondingto
theselogicaladdressesisreferredtoasaphysicaladdressspace.
Theruntimemappingfromvirtualtophysicaladdressesisdonebythe
memorymanagementunit(MMU),whichisahardwaredevice.
Thebaseregisteriscalledarelocationregister.Thevalueintherelocation
registerisaddedtoeveryaddressgeneratedbyauserprocessatthetimeitis
sent
tomemory.Forexample,ifthebaseisat13000,thenanattemptbytheuserto
addresslocation0dynamicallyrelocatedtolocation14,000anaccessto
location
347ismappedtolocation13347.TheMSDOSoperatingsystemrunningonthe
Intel80x86familyofprocessorsusesfourrelocationregisterswhenloadingand
runningprocesses.
Theuserprogramneverseestherealphysicaladdresses.Theprogramcan
createapointertolocation347storeitmemory,manipulateit,compareitto
other
addressesallasthenumber347.
Theuserprogramdealswithlogicaladdresses.Thememorymapping
hardwareconvertslogicaladdressesintophysicaladdressedLogicaladdresses
(in
therange0tomax)andphysicaladdresses(intherangeR+0toR+maxfora
basevalueR).Theusergeneratesonlylogicaladdresses.
Theconceptofalogicaladdressspacethatisboundtoaseparatephysical
addressspaceiscentraltopropermemorymanagement.

7.2Swapping
Aprocess,canbeswappedtemporarilyoutofmemorytoabackingstore,
andthenbroughtbackintomemoryforcontinuedexecution.Assumea
multiprogrammingenvironmentwitharoundrobinCPUschedulingalgorithm.
Whenaquantumexpires,thememorymanagerwillstarttoswapouttheprocess
thatjustfinished,andtoswapinanotherprocesstothememoryspacethathas
beenfreed(Fig7.2).Wheneachprocessfinishesitsquantum,itwillbe
swapped
withanotherprocess.
Fig7.2Swappingoftwoprocessesusingadiskasablockingstore
Avariantofthisswappingpolicyisusedforprioritybasedscheduling
algorithms.Ifahigherpriorityprocessarrivesandwantsservice,thememory
managercanswapoutthelowerpriorityprocesssothatitcanloadandexecute
the
higherpriorityprocess.Whenthehigherpriorityprocessfinishes,the
lowerpriority
processcanbeswappedbackinandcontinued.Thisvariantofswappingis
sometimescalledrollout,rollin.Aprocessisswappedoutwillbeswappedback
intothesamememoryspacethatitoccupiespreviously.Ifbindingisdoneat
assemblyorloadtime,thentheprocesscannotbemovedtodifferentlocation.If
executiontimebindingisbeingused,thenitispossibletoswapaprocessintoa
differentmemoryspace.
Swappingrequiresabackingstore.Thebackingstoreiscommonlyafastdisk.It
is
largeenoughtoaccommodatecopiesofallmemoryimagesforallusers.The
systemmaintainsareadyqueueconsistingofallprocesseswhosememory
images
areonthebackingstoreorinmemoryandarereadytorun.
Thecontextswitchtimeinsuchaswappingsystemisfairlyhigh.Letusassume
thattheuserprocessisofsize100Kandthebackingstoreisastandardharddisk
withtransferrateof1megabytepersecond.Theactualtransferofthe100K
processtoorfrommemorytakes
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

33/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

100K/1000Kpersecond=1/10second
=100milliseconds

7.3ContiguousAllocation
Themainmemorymustaccommodateboththeoperatingsystemandthe
varioususerprocesses.Thememoryisusuallydividedintotwopartitions,one
for
theresidentoperatingsystem,andonefortheuserprocesses.
Toplacetheoperatingsysteminlowmemory.Thus,weshalldiscussonly
mesituationwheretheoperatingsystemresidesinlowmemory(Figure8.5).
The
developmentoftheothersituationissimilar.CommonOperatingSystemis
placed
inlowmemory.
7.3.1SinglePartitionAllocation
Iftheoperatingsystemisresidinginlowmemory,andtheuserprocessesare
executinginhighmemory.Andoperatingsystemcodeanddataareprotected
from
changesbytheuserprocesses.Wealsoneedprotecttheuserprocessesfromone
another.Wecanprovidethis2protectionbyusingarelocationregisters.
Therelocationregistercontainsthevalueofthesmallestphysicaladdress
thelimitregistercontainstherangeoflogicaladdresses(forexample,relocation
=
100,040andlimit=74,600).Withrelocationandlimitregisters,eachlogical
addressmustbelessthanthelimitregistertheMMUmapsthelogicaladdress
dynamicallybyaddingthevalueintherelocationregister.Thismappedaddress
is
senttomemory.
Therelocationregisterschemeprovidesaneffectivewaytoallowthe
operatingsystemsizetochangedynamically.
7.3.2MultiplePartitionAllocation
Oneofthesimplestschemesformemoryallocationistodividememoryinto
anumberoffixedsizedpartitions.Eachpartitionmaycontainexactlyone
process.
Thus,thedegreeofmultiprogrammingisboundbythenumberofpartitions.
When
apartitionisfree,aprocessisselectedfromtheinputqueueandisloadedinto
the
freepartition.Whentheprocessterminates,thepartitionbecomesavailablefor
anotherprocess.
Theoperatingsystemkeepsatableindicatingwhichpartsofmemoryare
availableandwhichareoccupied.Initially,allmemoryisavailableforuser
processes,andisconsideredasonelargeblock,ofavailablememory,ahole.
When
aprocessarrivesandneedsmemory,wesearchforaholelargeenoughforthis
process.
Forexample,assumethatwehave2560Kofmemoryavailableanda
residentoperatingsystemof400K.Thissituationleaves2160Kforuser
processes.
FCFSjobscheduling,wecanimmediatelyallocatememorytoprocessesP1,P2,
P3.Holessize260Kthatcannotbeusedbyanyoftheremainingprocessesin
the
inputqueue.UsingaroundrobinCPUschedulingwithaquantumof1time
unit,
processwillterminateattime14,releasingitsmemory.
MemoryallocationisdoneusingRoundRobinSequenceasshowninfig.
Whenaprocessarrivesandneedsmemory,wesearchthissetforaholethatis
largeenoughforthisprocess.Iftheholeistoolarge,itissplitintotwo:Onepart
is
allocatedtothearrivingprocesstheotherisreturnedtothesetofholes.Whena
processterminates,itreleasesitsblockofmemory,whichisthenplacedbackin
thesetofholes.Ifthenewholeisadjacenttootherholes,wemergethese
adjacent
holestoformonelargerhole.
Thisprocedureisaparticularinstanceofthegeneraldynamicstorageallocation
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

34/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

problem,whichishowtosatisfyarequestofsizenfromalistoffree
holes.Therearemanysolutionstothisproblem.Thesetofholesissearchedto
determinewhichholeisbesttoallocate,firstfit,bestfit,andworstfitarethe
most
commonstrategiesusedtoselectafreeholefromthesetofavailableholes.
Firstfit:Allocatethefirstholethatisbigenough.Searchingcanstarteither
atthebeginningofthesetofholesorwherethepreviousfirstfitsearch
ended.Wecanstopsearchingassoonaswefindafreeholethatislarge
enough.
Bestfit:Allocatethesmallestholethatisbigenough.Wemustsearchthe
entirelist,unlessthelistiskeptorderedbysize.Thisstrategyproducesthe
smallestleftoverhole.
Worstfit:Allocatethelargesthole.Again,wemustsearchtheentirelist
unlessitissortedbysize.Thisstrategyproducesthelargestleftoverhole
whichmaybemoreusefulthanthesmallerleftoverholefromabestt
approach.
7.3.3ExternalandInternalFragmentation
Asprocessesareloadedandremovedfrommemory,thefreememoryspace
isbrokenintolittlepieces.Externalfragmentationexistswhenenoughtothe
memoryspaceexiststosatisfyarequest,butitisnotcontiguousstorageis
fragmentedintoalargenumberofsmallholes.
Dependingonthetotalamountofmemorystorageandtheaverageprocess
size,externalfragmentationmaybeeitheraminororamajorproblem.
GivenNallocatedblocks,another0.5Nblockswillbelostdueto
fragmentation.Thatis,onethirdofmemorymaybeunusable.Thispropertyis
knownasthe50percentrule.
Internalfragmentationmemorythatisinternaltopartition,butisnotbeing
used.

7.4Paging
Externalfragmentationisavoidedbyusingpaging.Inthisphysicalmemory
isbrokenintoblocksofthesamesizecalledpages.Whenaprocessistobe
executed,itspagesareloadedintoanyavailablememoryframes.Everyaddress
generatedbytheCPUisdividedintoanytwoparts:apagenumber(p)anda
page
offset(d)(Fig7.3).Thepagenumberisusedasanindexintoapagetable.The
pagetablecontainsthebaseaddressofeachpageinphysicalmemory.Thisbase
addressiscombinedwiththegageoffsettodefinethephysicalmemoryaddress
thatissenttothememoryunit.
Fig7.3PagingHardware
Thepagesizelikeisdefinedbythehardware.Thesizeofapageistypically
apowerof2varyingbetween512bytesand8192bytesperpage,dependingon
the
computerarchitecture.Theselectionofapowerof2asapagesizemakesthe
translationofalogicaladdressintoapagenumberandpageoffset.lfthesizeof
logicaladdressspaceis2m,andapagesizeis2naddressingunits(bytesor
words),
thenthehighordermnbitsofalogicaladdressdesignatethepagenumber,
and
thenloworderbitsdesignatethepageoffset.Thus,thelogicaladdressisas
follows:
pagenumber
pageoffset
pd
mnn
wherepisanindexintothepagetableanddisthedisplacementwithinthe
page.
Pagingisaformofdynamicrelocation.Everylogicaladdressisboundby
thepaginghardwaretosomephysicaladdress.
Whenweuseapagingscheme,wehavenoexternalfragmentation:Anyfree
framecanbeallocatedtoaprocessthatneedsit.
Ifprocesssizeisindependentofpagesize,wecanhaveinternal
fragmentationtoaverageonehalfpageperprocess.
Whenaprocessarrivesinthesystemtobeexecuted,itssize,expressedin
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

35/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

pages,isexamined.Eachpageoftheprocessneedsoneframe.Thus,ifthe
process
requiresnpages,theremustbeatleastnframesavailableinmemory.Ifthere
aren
framesavailable,theyareallocatedtothisarrivingprocess.Thefirstpageofthe
processisloadedintooneoftheallocatedframesandtheframenumberisputin
thepagetableforthisprocess.Thenextpageisloadedintoanotherframe,and
its
framenumberisputintothepagetable,andsoon.
Theuserprogramviewsthatmemoryasonesinglecontiguousspace,
containingonlythisoneprogram.Buttheuserprogramisscatteredthroughout
physicalmemoryandlogicaladdressesaretranslatedintophysicaladdresses.
Theoperatingsystemismanagingphysicalmemory,itmustbeawareofthe
allocationdetailsofphysicalmemory:whichframesareallocated,whichframes
areavailable,howmanytotalframesthereare,andsoon.Thisinformationis
generallykeptinadatastructurecalledaframetable.Theframetablehasone
entryforeachphysicalpageframe,indicatingwhetherthelatterisfreeallocated
and,ifitisallocated,towhichpageofwhichprocessorprocesses.
Theoperatingsystemmaintainsacopyofthepagetableforeachprocess.
Pagingthereforeincreasesthecontextswitchtime.

7.5Segmentation
Auserprogramcanbesubdividedusingsegmentation,inwhichtheprogram
anditsassociateddataaredividedintoanumberofsegments.Itisnotrequired
thatallsegmentsofallprogramsbeofthesamelength,althoughthereisa
maximumsegmentlength.Aswithpaging,alogicaladdressusingsegmentation
consistsoftwoparts,inthiscaseasegmentnumberandanoffset.
Becauseoftheuseofunequalsizesegments,segmentationissimilartodynamic
partitioning.Insegmentation,aprogrammayoccupymorethanonepartition,
and
thesepartitionsneednotbecontiguous.Segmentationeliminatesinternal
fragmentationbut,likedynamicpartitioning,itsuffersfromexternal
fragmentation.However,becauseaprocessisbrokenupintoanumberof
smaller
pieces,theexternalfragmentationshouldbeless.Whereaspagingisinvisibleto
theprogrammer,segmentationusuallyvisibleandisprovidedasaconvenience
for
organizingprogramsanddata.
Anotherconsequenceofunequalsizesegmentsisthatthereisnosimple
relationshipbetweenlogicaladdressesandphysicaladdresses.Segmentation
schemewouldmakeuseofasegmenttableforeachprocessandalistoffree
blocksofmainmemory.Eachsegmenttableentrywouldhavetoasinpaging
give
thestartingaddressinmainmemoryofthecorrespondingsegment.Theentry
shouldalsoprovidethelengthofthesegment,toassurethatinvalidaddresses
are
notused.WhenaprocessenterstheRunningstate,theaddressofitssegment
table
isloadedintoaspecialregisterusedbythememorymanagementhardware.
Consideranaddressofn+mbits,wheretheleftmostnbitsarethesegment
numberandtherightmostmbitsaretheoffset.Thefollowingstepsareneeded
for
addresstranslation:
Extractthesegmentnumberastheleftmostnbitsofthelogicaladdress.
Usethesegmentnumberasanindexintotheprocesssegmenttabletofind
thestartingphysicaladdressofthesegment.
Comparetheoffset,expressedintherightmostmbits,tothelengthofthe
segment.Iftheoffsetisgreaterthanorequaltothelength,theaddressis
invalid.
Thedesiredphysicaladdressisthesumofthestartingphysicaladdressof
thesegmentplustheoffset.
Segmentationandpagingcanbecombinedtohaveagoodresult.

7.6Summary
Memorymanagementalgorithmsformultiprogrammedoperatingsystems
rangefromthesimplesingleusersystemapproachtopagedsegmentation.The
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

36/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

mostimportantdeterminantofthemethodusedinaparticularsystemisthe
hardwareprovided,everymemoryaddressgeneratedbytheCPUmustbe
checked
forlegalityandpossiblymappedtoaphysicaladdress,thecheckingcannotbe
implementedinsoftware.Hence,weareconstrainedbythehardwareavailable.
Thevariousmemorymanagementalgorithms(continuousallocation,paging,
segmentation,andcombinationsofpagingandsegmentation)differinmany
aspects.Incomputingdifferentmemorymanagementstrategies,weuse
hardware
support,performance,fragmentation,relocation,swapping,sharingand
protection.

7.7ModelQuestion
Q.1Differentiateinternalandexternalfragmentation?
Q.2Explainsegmentation?
Q.3Whatarehardwareisrequiredforpaging?
Q.4Writeanoteonvirtualmemory?
Q.5ExplainPagereplacementalgorithmindetail?
Q.6comparedemandpagingandsegmentation?
Q.7Explainpagereplacementalgorithm?

CHAPTER8
VIRTUALMEMORY
UnitStructure
8.0Objectives
8.1VirtualMemory
8.2DemandPaging
8.3Performanceofdemandpaging
8.4VirtualMemoryConcepts
8.5PageReplacementAlgorithms
8.6AllocationAlgorithms
8.7Summary
8.8ModelQuestion

8.0Objective
Todescribethebenefitsofavirtualmemorysystem.
Toexplaintheconceptsofdemandpaging,pagereplacementalgorithms,
andallocationofpageframes.
Todiscusstheprincipleoftheworkingsetmodel.

8.1VirtualMemory
Virtualmemoryisatechniquethatallowstheexecutionofprocessthatmay
notbecompletelyinmemory.Themainvisibleadvantageofthisschemeis
thatprogramscanbelargerthanphysicalmemory.
Virtualmemoryistheseparationofuserlogicalmemoryfromphysical
memorythisseparationallowsanextremelylargevirtualmemorytobe
providedforprogrammerswhenonlyasmallerphysicalmemoryisavailable
(Fig8.1).
Followingarethesituations,whenentireprogramisnotrequiredtoload
fully.
1.Userwrittenerrorhandlingroutinesareusedonlywhenanerroroccursin
thedataorcomputation.
2.Certainoptionsandfeaturesofaprogrammaybeusedrarely.
3.Manytablesareassignedafixedamountofaddressspaceeventhoughonly
asmallamountofthetableisactuallyused.
Theabilitytoexecuteaprogramthatisonlypartiallyinmemorywould
countermanybenefits.
1.LessnumberofI/Owouldbeneededtoloadorswapeachuserprograminto
memory.
2.Aprogramwouldnolongerbeconstrainedbytheamountofphysical
memorythatisavailable.
3.Eachuserprogramcouldtakelessphysicalmemory,moreprogramscould
berunthesametime,withacorrespondingincreaseinCPUutilizationand
throughput.
Fig.8.1Diagramshowingvirtualmemorythatislargerthanphysicalmemory.
Virtualmemoryiscommonlyimplementedbydemandpaging.Itcanalsobe
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

37/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

implementedinasegmentationsystem.Demandsegmentationcanalsobeused
to
providevirtualmemory.

8.2DemandPaging
Ademandpagingissimilartoapagingsystemwithswapping(Fig8.2).
Whenwewanttoexecuteaprocess,weswapitintomemory.Ratherthan
swappingtheentireprocessintomemory.
Whenaprocessistobeswappedin,thepagerguesseswhichpageswillbe
usedbeforetheprocessisswappedoutagainInsteadofswappinginawhole
process,thepagerbringsonlythosenecessarypagesintomemory.Thus,it
avoids
readingintomemorypagesthatwillnotbeusedinanyway,decreasingtheswap
timeandtheamountofphysicalmemoryneeded.
Hardwaresupportisrequiredtodistinguishbetweenthosepagesthatarein
memoryandthosepagesthatareonthediskusingthevalidinvalidbitscheme.
Wherevalidandinvalidpagescanbecheckedcheckingthebitandmarkinga
page
willhavenoeffectiftheprocessneverattemptstoaccessthepages.Whilethe
processexecutesandaccessespagesthatarememoryresident,execution
proceeds
normally.
Fig.8.2Transferofapagedmemorytocontinuousdiskspace
Accesstoapagemarkedinvalidcausesapagefaulttrap.Thistrapisthe
resultoftheoperatingsystem'sfailuretobringthedesiredpageintomemory.
But
pagefaultcanbehandledasfollowing(Fig8.3):
Fig.8.3Stepsinhandlingapagefault
1.Wecheckaninternaltableforthisprocesstodeterminewhetherthe
referencewasavalidorinvalidmemoryaccess.
2.Ifthereferencewasinvalid,weterminatetheprocess.If.itwasvalid,butwe
havenotyetbroughtinthatpage,wenowpageinthelatter.
3.Wefindafreeframe.
4.Wescheduleadiskoperationtoreadthedesiredpageintothenewly
allocatedframe.
5.Whenthediskreadiscomplete,wemodifytheinternaltablekeptwiththe
processandthepagetabletoindicatethatthepageisnowinmemory.
6.Werestarttheinstructionthatwasinterruptedbytheillegaladdresstrap.The
processcannowaccessthepageasthoughithadalwaysbeenmemory.
Therefore,theoperatingsystemreadsthedesiredpageintomemoryandrestarts
theprocessasthoughthepagehadalwaysbeeninmemory.
Thepagereplacementisusedtomaketheframefreeiftheyarenotinused.If
noframeisfreethenotherprocessiscalledin.
8.2.1AdvantagesofDemandPaging:
1.Largevirtualmemory.
2.Moreefficientuseofmemory.
3.Unconstrainedmultiprogramming.Thereisnolimitondegreeof
multiprogramming.
8.2.2DisadvantagesofDemandPaging:
1.Numberoftablesandamountofprocessoroverheadforhandlingpage
interruptsaregreaterthaninthecaseofthesimplepagedmanagement
techniques.
2.duetothelackofanexplicitconstraintsonajobsaddressspacesize.

8.3PageReplacementAlgorithm
Therearemanydifferentpagereplacementalgorithms.Weevaluatean
algorithmbyrunningitonaparticularstringofmemoryreferenceand
computing
thenumberofpagefaults.Thestringofmemoryreferencesiscalledreference
string.Referencestringsaregeneratedartificiallyorbytracingagivensystem
and
recordingtheaddressofeachmemoryreference.Thelatterchoiceproducesa
large
numberofdata.
1.Foragivenpagesizeweneedtoconsideronlythepagenumber,notthe
entireaddress.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

38/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

2.ifwehaveareferencetoapagep,thenanyimmediatelyfollowingreferences
topagepwillnevercauseapagefault.Pagepwillbeinmemoryafterthe
firstreferencetheimmediatelyfollowingreferenceswillnotfault.
Eg:considertheaddresssequence
0100,0432,0101,0612,0102,0103,0104,0101,0611,0102,0103,
0104,0101,0610,0102,0103,0104,0104,0101,0609,0102,0105
andreduceto1,4,1,6,1,6,1,6,1,6,1
Todeterminethenumberofpagefaultsforaparticularreferencestringand
pagereplacementalgorithm,wealsoneedtoknowthenumberofpageframes
available.Asthenumberofframesavailableincrease,thenumberofpagefaults
willdecrease.
8.3.1FIFOAlgorithm
ThesimplestpagereplacementalgorithmisaFIFOalgorithm.AFIFO
replacementalgorithmassociateswitheachpagethetimewhenthatpagewas
broughtintomemory.Whenapagemustbereplaced,theoldestpageischosen.
WecancreateaFIFOqueuetoholdallpagesinmemory.
Thefirstthreereferences(7,0,1)causepagefaults,andarebroughtinto
theseemptyeg.7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1andconsider3frames.
Thisreplacementmeansthatthenextreferenceto0willfault.Page1isthen
replacedbypage0.
8.3.2OptimalAlgorithm
Anoptimalpagereplacementalgorithmhasthelowestpagefaultrateofall
algorithms.Anoptimalpagereplacementalgorithmexists,andhasbeencalled
OPTorMIN.Itissimply
Replacethepagethatwillnotbeused
forthelongestperiodoftime.
Nowconsiderthesamestringwith3emptyframes.
Thereferencetopage2replacespage7,because7willnotbeuseduntil
reference18,whereaspage0willbeusedat5,andpage1at14.Thereference
to
page3replacespage1,aspage1willbethelastofthethreepagesinmemoryto
bereferencedagain.OptimalreplacementismuchbetterthanaFIFO.
Theoptimalpagereplacementalgorithmisdifficulttoimplement,becauseit
requiresfutureknowledgeofthereferencestring.
8.3.3LRUAlgorithm
TheFIFOalgorithmusesthetimewhenapagewasbroughtintomemory
theOPTalgorithmusesthetimewhenapageistobeused.InLRUreplacethe
pagethathasnotbeenusedforthelongestperiodoftime.
LRUreplacementassociateswitheachpagethetimeofthatpage'slastuse.
Whenapagemustbereplaced,LRUchoosesthatpagethathasnotbeenused
for
thelongestperiodoftime.
LetSRbethereverseofareferencestringS,thenthepagefaultrateforthe
OPTalgorithmonSisthesameasthepagefaultratefortheOPTalgorithmon
SR.

8.3.4LRUApproximationAlgorithms
Somesystemsprovidenohardwaresupport,andotherpagereplacement
algorithm.Manysystemsprovidesomehelp,however,intheformofareference
bit.Thereferencebitforapageisset,bythehardware,wheneverthatpageis
referenced.Referencebitsareassociatedwitheachentryinthepagetable
Initially,
allbitsarecleared(to0)bytheoperatingsystem.Asauserprocessexecutes,the
bitassociatedwitheachpagereferencedisset(to1)bythehardware.
8.3.4.1AdditionalReferenceBitsAlgorithm
Theoperatingsystemshiftsthereferencebitforeachpageintothehighorder
orofits8bitbyte,shiftingtheotherbitsright1bit,discardingtheloworder
bit.
These8bitshiftregisterscontainthehistoryofpageuseforthelasteight
timeperiods.Iftheshiftregistercontains00000000,thenthepagehasnotbeen
usedforeighttimeperiodsapagethatisusedatleastonceeachperiodwould
haveashiftregistervalueof11111111.
8.3.4.2SecondChanceAlgorithm
ThebasicalgorithmofsecondchancereplacementisaFIFOreplacement
algorithm.Whenapagegetsasecondchance,itsreferencebitisclearedandits
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

39/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

arrivaleisresettothecurrenttime.
8.3.4.3EnhancedSecondChanceAlgorithm
Thesecondchancealgorithmdescribedabovecanbeenhancedby
consideringtroththereferencebitandthemodifybitasanorderedpair.
1.(0,0)neitherrecentlyusednormodifiedbestpagetoreplace.
2.(0,1)notrecentlyusedbutmodifiednotquiteasgood,becausethepage
willneedtobewrittenoutbeforereplacement.
3.(1,0)recentlyusedbutcleanprobablywillbeusedagainsoon.
4.(1,1)recentlyusedandmodifiedprobablywillbeusedagain,andwrite
outwillbeneededbeforereplacingit

8.4CountingAlgorithms
Therearemanyotheralgorithmsthatcanbeusedforpagereplacement.
LFUAlgorithm:Theleastfrequentlyused(LFU)pagereplacementalgorithm
requiresthatthepagewiththesmallestcountbereplaced.Thisalgorithmsuffers
fromthesituationinwhichapageisusedheavilyduringtheinitialphaseofa
process,butthenisneverusedagain.
MFUAlgorithm:Themostfrequentlyused(MFU)pagereplacement
algorithm
isbasedontheargumentthatthepagewiththesmallestcountwasprobablyjust
broughtinandhasyettobeused.

8.5PageBufferingAlgorithm
Whenapagefaultoccurs,avictimframeischosenasbefore.However,the
desiredpageisreadintoafreeframefromthepoolbeforethevictimiswritten
out.
Thisprocedureallowstheprocesstorestartassoonaspossible,withoutwaiting
forthevictimpagetobewrittenout.Whenthevictimislaterwrittenout,its
frame
isaddedtothefreeframepool.
WhentheFIFOreplacementalgorithmmistakenlyreplacesapage
mistakenlyreplacesapagethatisstillinactiveuse,thatpageisquickly
retrieved
fromthefreeframebuffer,andnoI/Oisnecessary.Thefreeframebuffer
provides
protectionagainsttherelativelypoor,butsimple,FIFOreplacementalgorithm.

8.6Summary
Itisdesirabletobeabletoexecuteaprocesswhoselogicaladdressspace
largerthantheavailablephysicaladdressspace.Virtualmemoryisatechnique
that
enablesustomapalogicaladdressspaceontoasmallerphysicalmemory.
Virtual
memoryallowsustorunextremelylargeprocessesandtoraisethedegreeof
multiprogramming,increasingCPUutilization.Virtualmemoryalsoenablesus
to
useanefficienttypeofprocesscreationknownascopyonwrite,wherein
parent
andchildprocessesshareactualpagesofmemory.
Virtualmemoryiscommonlyimplementedbydemandpaging.puredemand
pagingneverbringsinapageuntilthatpageisreferenced.Thefirstreference
causespagefaulttotheoperatingsystem.Iftotalmemoryrequirementsexceed
the
capacityofphysicalmemory,thenitmaybenecessarytoreplacepagesfrom
memorytofreeframesfornewpages.Variouspagereplacementalgorithmare
used.
Inadditiontoapagereplacementalgorithm,aframeallocationpolicyis
needed.Allocationcanbefixed,suggestinglocalpagereplacement,ordynamic,
suggestingglobalreplacement.

8.7ModelQuestion
Q.1DefineandexplainVirtualMemory?
Q.2ExplainadvantagesanddisadvantagesDemandPaging
Q.3DefineandexplainPerformanceofdemandpaging?
Q.4DescribePageReplacementAlgorithms?
Q.5ExplainvariousAllocationAlgorithms?

CHAPTER9
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

40/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

I/OHARDWARE
UnitStructure
9.0Objectives
9.1PrincipalofI/OHardware
9.2Polling
9.3I/ODevices
9.4DeviceControllers
9.5DirectMemoryAccess
9.6Summary
9.7ModelQuestion

9.0Objective
Explorethestructureofanoperatingsystem'sI/Osubsystem.
DiscusstheprinciplesofI/Ohardwareanditscomplexity.

9.1I/OHardware
Computersoperateagreatmanykindsofdevices.Generaltypesinclude
storagedevices(disks,tapes),transmissiondevices(networkcards,
modems),andhumaninterfacedevices(screen,keyboard,mouse).
Adevicecommunicateswithacomputersystembysendingsignalsovera
cableoreventhroughtheair.Thedevicecommunicateswiththemachine
viaaconnectionpointtermedaport(forexample,aserialport).Ifoneor
moredevicesuseacommonsetofwires,theconnectioniscalledabus.
WhendeviceAhasacablethatplugsintodeviceB,anddeviceBhasa
cablethatplugsintodeviceC,anddeviceCplugsintoaportonthe
computer,thisarrangementiscalledadaisychain.Itusuallyoperatesasa
bus.
Acontrollerisacollectionofelectronicsthatcanoperateaport,abus,ora
device.Aserialportcontrollerisanexampleofasimpledevicecontroller.
Itisasinglechipinthecomputerthatcontrolsthesignalsonthewiresofa
serialport.
TheSCSIbuscontrollerisoftenimplementedasaseparatecircuitboard(a
hostadapter)thatplugsintothecomputer.Ittypicallycontainsaprocessor,
microcode,andsomeprivatememorytoenableittoprocesstheSCSI
protocolmessages.Somedeviceshavetheirownbuiltincontrollers.
AnI/Oporttypicallyconsistsoffourregisters,calledthestatus,control,
datain,anddataoutregisters.Thestatusregistercontainsbitsthatcanbe
readbythehost.Thesebitsindicatestatessuchaswhetherthecurrent
commandhascompleted,whetherabyteisavailabletobereadfromthe
datainregister,andwhethertherehasbeenadeviceerror.Thecontrol
registercanbewrittenbythehosttostartacommandortochangethemode
ofadevice.Forinstance,acertainbitinthecontrolregisterofaserialport
choosesbetweenfullduplexandhalfduplexcommunication,another
enablesparitychecking,athirdbitsetsthewordlengthto7or8bits,and
otherbitsselectoneofthespeedssupportedbytheserialport.
Thedatainregisterisreadbythehosttogetinput,andthedataoutregister
iswrittenbythehosttosendoutput.Thedataregistersaretypically1to4
bytes.SomecontrollershaveFIFOchipsthatcanholdseveralbytesofinput
oroutputdatatoexpandthecapacityofthecontrollerbeyondthesizeofthe
dataregister.AFIFOchipcanholdasmallburstofdatauntilthedeviceor
hostisabletoreceivethosedata.

9.2POLLING
Incompleteprotocolforinteractionbetweenthehostandacontrollercanbe
intricate,butthebasichandshakingnotionissimple.Thecontrollerindicates
itsstatethroughthebusybitinthestatusregister.(Recallthattosetabit
meanstowritea1intothebit,andtoclearabitmeanstowritea0intoit.)
Thecontrollersetsthebusybitwhenitisbusyworking,andclearsthebusy
bitwhenitisreadytoacceptthenextcommand.Thehostsignalsitswishes
viathecommandreadybitinthecommandregister.Thehostsetsthe
commandreadybitwhenacommandisavailableforthecontrollerto
execute.
Forthisexample,thehostwritesoutputthroughaport,coordinatingwiththe
controllerbyhandshakingasfollows.
1.Thehostrepeatedlyreadsthebusybituntilthatbitbecomesclear.
2.Thehostsetsthewritebitinthecommandregisterandwritesabyteintothe
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

41/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

dataoutregister.
3.Thehostsetsthecommandreadybit.
4.Whenthecontrollernoticesthatthecommandreadybitisset,itsetsthe
Busy.
5.Thecontrollerreadsthecommandregisterandseesthewritecommand.
6.Itreadsthedataoutregistertogetthebyte,anddoestheI/Otothedevice.
7.Thecontrollerclearsthecommandreadybit,clearstheerrorbitinthe
statusregistertoindicatethatthedeviceI/Osucceeded,andclearsthebusy
bittoindicatethatitisfinished.
Thehostisbusywaitingorpolling:Itisinaloop,readingthestatusregister
overandoveruntilthebusybitbecomesclear.Ifthecontrolleranddevice
arefast,thismethodisareasonableone.Butifthewaitmaybelong,the
hostshouldprobablyswitchtoanothertask

9.3I/ODevices
CategoriesofI/ODevices
1.Humanreadable
2.machinereadable
3.Communication
1.HumanReadableissuitableforcommunicatingwiththecomputeruser.
Examplesareprinters,videodisplayterminals,keyboardetc.
2.MachineReadableissuitableforcommunicatingwithelectronicequipment.
Examplesarediskandtapedrives,sensors,controllersandactuators.
3.Communicationissuitableforcommunicatingwithremotedevices.
Examplesaredigitallinedriversandmodems.
DifferencesbetweenI/ODevices
1.Datarate:theremaybedifferencesofseveralordersofmagnitudebetween
thedatatransferrates.
2.Application:Differentdeviceshavedifferentuseinthesystem.
3.ComplexityofControl:Adiskismuchmorecomplexwhereasprinter
requiressimplecontrolinterface.
4.Unitoftransfer:Datamaybetransferredasastreamofbytesorcharacters
orinlargerblocks.
5.Datarepresentation:Differentdataencodingschemesareusedfordifferent
devices.
6.ErrorConditions:Thenatureoferrorsdifferswidelyfromonedeviceto
another.

9.4DirectMemoryAccess
Aspecialcontrolunitmaybeprovidedtoallowtransferofablockofdata
directlybetweenanexternaldeviceandthemainmemory,without
continuousinterventionbytheprocessor.ThisapproachiscalledDirect
MemoryAccess(DMA).
DMAcanbeusedwitheitherpollingorinterruptsoftware.DMAis
particularlyusefulondeviceslikedisks,wheremanybytesofinformation
canbetransferredinsingleI/Ooperations.Whenusedinconjunctionwith
aninterrupt,theCPUisnotifiedonlyaftertheentireblockofdatahasbeen
transferred.Foreachbyteorwordtransferred,itmustprovidethememory
addressandallthebussignalsthatcontrolthedatatransfer.
Interactionwithadevicecontrollerismanagedthroughadevicedriver.
Devicedriversarepartoftheoperatingsystem,butnotnecessarilypartof
theOSkernel.Theoperatingsystemprovidesasimplifiedviewofthe
devicetouserapplications(e.g.,characterdevicesvs.blockdevicesin
UNIX).Insomeoperatingsystems(e.g.,Linux),devicesarealsoaccessible
throughthe/devfilesystem.
Insomecases,theoperatingsystembuffersdatathataretransferredbetween
adeviceandauserspaceprogram(diskcache,networkbuffer).Thisusually
increasesperformance,butnotalways.

9.5DeviceControllers
AcomputersystemcontainsamultitudeofI/Odevicesandtheirrespective
controllers:
networkcard
graphicsadapter
diskcontroller
DVDROMcontroller
serialport
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

42/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

USB
soundcard

9.6Summary
ThebasichardwareelementsinvolvedinI/Obuses,devicecontrollers,and
thedevicethemselves.Theworkofmovingdatabetweendevicesandmain
memoryisperformedbytheCPUasprogrammedI/OorisoffloadedtoaDMA
controller.Thekernelmodulethatcontrolsadevicedriver.
Thesystemcallinterfaceprovidedtoapplicationsisdesignedtohandle
severalbasiccategoriesofhardware,includingblockdevices,characterdevices,
memorymappedfiles,networksockets,andprogrammedintervaltimers.The
systemcallsusuallyblocktheprocessesthatissuethem,butnonblockingand
asynchronouscallsareusedbythekernelitselfandbyapplicationsthatmustnot
sleepwhilewaitingforanI/Ooperationtocomplete.
Thekernel'sI/Osubsystemprovidesnumerousservices.Amongtheseare
I/Oscheduling,buffering,caching.Spooling,devicereservation,anderror
handling.

9.7ModelQuestion
Q.1DefineandExplainDirectMemoryAccess?
Q.2Explaindevicecontrollers?
Q.3ExplainconceptofI/OHardware?
Q.4ExplainconceptofPolling?
Q.5ExplainI/Odevices?

CHAPTER10
I/OSOFTWARE
UnitStructure
10.0Objectives
10.1PrincipleofI/OSoftware
10.1.1Interrupts
10.2.2ApplicationI/OInterfaced
10.1.3ClocksandTimers
10.1.4BlockingandNonblockingI/O
10.2KernelI/OSubsystem
10.2.1Scheduling
10.2.2Buffering
10.2.3Caching
10.2.3SpoolingandDeviceReservation
10.2.4ErrorHandling
10.3DeviceDrivers
10.4Summary
10.5ModelQuestion

10.0Objective
Explorethestructureofanoperatingsystem'sI/Osubsystem.
DiscusstheprinciplesofI/Osoftware.
ProvidedetailsoftheperformanceaspectsofI/Osoftware.

10.1PRINCIPLESOFI/OSOFTWARE
10.1.1Interrupts
TheCPUhardwarehasawirecalledtheinterruptrequestlinethattheCPU
sensesafterexecutingeveryinstruction.WhentheCPUdetectsthata
controllerhasassertedasignalontheinterruptrequestline,theCPUsavesa
smallamountofstate,suchasthecurrentvalueoftheinstructionpointer,
andjumpstotheinterrupthandlerroutineatafixedaddressinmemory.
Theinterrupthandlerdeterminesthecauseoftheinterrupt,performsthe
necessaryprocessing,andexecutesareturnfrominterruptinstructionto
returntheCPUtotheexecutionstatepriortotheinterrupt.Wesaythatthe
devicecontrollerraisesaninterruptbyassertingasignalontheinterrupt
requestline,theCPUcatchestheinterruptanddispatchestotheinterrupt
handler,andthehandlerclearstheinterruptbyservicingthedevice.Figure
12.3summarizestheinterruptdrivenI/Ocycle.
ThisbasicinterruptmechanismenablestheCPUtorespondtoan
asynchronousevent,suchasadevicecontrollerbecomingreadyforservice.
Inamodernoperatingsystem,weneedmoresophisticatedinterrupthandling
features.
First,weneedtheabilitytodeferinterrupthandlingduringcritical
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

43/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

processing.Second,weneedanefficientwaytodispatchtotheproper
interrupthandlerforadevice,withoutfirstpollingallthedevicestosee
whichoneraisedtheinterrupt.Third,weneedmultilevelinterrupts,sothat
theoperatingsystemcandistinguishbetweenhighandlowpriority
interrupts,andcanrespondwiththeappropriatedegreeofurgency.
Inmoderncomputerhardware,thesethreefeaturesareprovidedbytheCPU
andbytheinterruptcontrollerhardware.
CPUshavetwointerruptrequestlines.Oneisthenonmaskableinterrupt,
whichisreservedforeventssuchasunrecoverablememoryerrors.The
secondinterruptlineismaskable.ItcanbeturnedoffbytheCPUbeforethe
executionofcriticalinstructionsequencesthatmustnotbeinterrupted.The
maskableinterruptisusedbydevicecontrollerstorequestservice.
Thisaddressisanoffsetinatablecalledtheinterruptvector.Thisvector
containsthememoryaddressesof.specializedinterrupthandlers.The
purposeofavectoredinterruptmechanismistoreducetheneedforasingle
interrupthandlertosearchallpossiblesourcesofinterruptstodetermine
whichoneneedsservice.
Theinterruptmechanismalsoimplementsasystemofinterruptpriority
levels.ThismechanismenablestheCPUtodeferthehandlingoflowpriority
interruptswithoutmaskingoffallinterrupts,andmakesitpossible
forahighpriorityinterrupttopreempttheexecutionofalowpriority
interrupt.
Theinterruptmechanismisalsousedtohandleawidevarietyofexceptions,
suchasdividingbyzero,accessingaprotectedornonexistentmemory
address,orattemptingtoexecuteaprivilegedinstructionfromusermode.
Asystemcallisafunctionthatiscalledbyanapplicationtoinvokeakernel
service.Thesystemcallcheckstheargumentsgivenbytheapplication,
buildsadatastructuretoconveytheargumentstothekernel,andthen
executesaspecialinstructioncalledasoftwareinterrupt,oratrap.
Interruptscanalsobeusedtomanagetheflowofcontrolwithinthekernel.
Ifthedisksaretobeusedefficiently,weneedtostartthenextI/Oassoonas
thepreviousonecompletes.Consequently,thekernelcodethatcompletesa
diskreadisimplementedbyapairofinterrupthandlers.Thehighpriority
handlerrecordstheI/Ostatus,clearsthedeviceinterrupt,startsthenext
pendingI/O,andraisesalowpriorityinterrupttocompletethework.The
correspondinghandlercompletestheuserlevelI/Obycopyingdatafrom
kernelbufferstotheapplicationspaceandthenbycallingtheschedulerto
placetheapplicationonthereadyqueue.
10.2.2ApplicationI/OInterfaced
StructuringtechniquesandinterfacesfortheoperatingsystemenableI/O
devicestobetreatedinastandard,uniformway.Forinstance,howan
applicationcanopenafileonadiskwithoutknowingwhatkindofdiskitis,
andhownewdisksandotherdevicescanbeaddedtoacomputerwithout
theoperatingsystembeingdisrupted.
Theactualdifferencesareencapsulatedinkenmodulescalleddevicedrivers
matinternallyarecustomtailoredtoeachdevicebutthatexportoneofthe
standardinterfaces.
Thepurposeofthedevicedriverlayeristohidethedifferencesamong
devicecontrollersfromtheI/Osubsystemofthekernel,muchastheI/O
systemcalls.
Characterstreamorblock.Acharacterstreamdevicetransfersbytesoneby
one,
whereasablockdevicetransfersablockofbytesasaunit.
Sequentialorrandomaccess.Asequentialdevicetransfersdatainafixed
order
thatisdeterminedbythedevice,whereastheuserofarandomaccessdevicecan
instructthedevicetoseektoanyoftheavailabledatastoragelocations.
Synchronousorasynchronous.Asynchronousdeviceisonethatperformsdata
transferswithpredictableresponsetimes.Anasynchronousdeviceexhibits
irregularorunpredictableresponsetimes.
Sharableordedicated.Asharabledevicecanbeusedconcurrentlybyseveral
processesorthreadsadedicateddevicecannot.
Speedofoperation.Devicespeedsrangefromafewbytespersecondtoafew
gigabytespersecond.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

44/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Readwrite,readonly,orwriteonly.Somedevicesperformbothinputand
output,butotherssupportonlyonedatadirection.Forthepurposeofapplication
access,manyofthesedifferencesarehiddenbytheoperatingsystem,andthe
devicesaregroupedintoafewconventionaltypes.
Operatingsystemsalsoprovidespecialsystemcallstoaccessafew
additionaldevices,suchasatimeofdayclockandatimer.Theperformance
andaddressingcharacteristicsofnetworkI/Odiffersignificantlyfromthose
ofdiskI/O,mostoperatingsystemsprovideanetworkI/Ointerfacethatis
differentfromthereadwriteseekinterfaceusedfordisks.
10.1.3ClocksandTimers
Mostcomputershavehardwareclocksandtimersthatprovidethreebasic
functions:
1.Givethecurrenttime
2.Givetheelapsedtime
3.SetatimertotriggeroperationXattimeT
Thesefunctionsareusedheavilybytheoperatingsystem,andalsobytime
sensitiveapplications.Thehardwaretomeasureelapsedtimeandtotrigger
operationsiscalledaprogrammableintervaltimer.
10.1.4BlockingandNonblockingI/O
Oneremainingaspectofthesystemcallinterfacerelatestothechoice
betweenblockingI/Oandnonblocking(asynchronous)I/O.Whenan
applicationcallsablockingsystemcall,theexecutionoftheapplicationis
suspended.Theapplicationismovedfromtheoperatingsystem'srunqueue
toawaitqueue.
Afterthesystemcallcompletes,theapplicationismovedbacktotherun
queue,whereitiseligibletoresumeexecution,atwhichtimeitwillreceive
thevaluesreturnedbythesystemcall.
SomeuserlevelprocessesneednonblockingI/O.

10.2KernelI/OSubsystem
KernelsprovidemanyservicesrelatedtoI/O.Theservicesthatwedescribe
areI/Oscheduling,bufferingcaching,spooling,devicereservation,anderror
handling.
10.2.1Scheduling
ToscheduleasetofI/Orequestsmeanstodetermineagoodorderinwhich
toexecutethem.Theorderinwhichapplicationsissuesystemcallsrarelyis
thebestchoice.Schedulingcanimproveoverallsystemperformance,can
sharedeviceaccessfairlyamongprocesses,andcanreducetheaverage
waitingtimeforI/Otocomplete.Operatingsystemdevelopersimplement
schedulingbymaintainingaqueueofrequestsforeachdevice.Whenan
applicationissuesablockingI/Osystemcall,therequestisplacedonthe
queueforthatdevice.
TheI/Oschedulerrearrangestheorderofthequeuetoimprovetheoverall
systemefficiencyandtheaverageresponsetimeexperiencedby
applications.
10.2.2Buffering
Abufferisamemoryareathatstoresdatawhiletheyaretransferredbetween
twodevicesorbetweenadevicearidanapplication.Bufferingisdonefor
threereasons.
Onereasonistocopewithaspeedmismatchbetweentheproducerand
consumerofadatastream.
Secondbufferwhilethefirstbufferiswrittentodisk.Aseconduseof
bufferingistoadaptbetweendevicesthathavedifferentdatatransfersizes.
AthirduseofbufferingistosupportcopysemanticsforapplicationI/O.
10.2.3Caching
Acacheisregionoffastmemorythatholdscopiesofdata.Accesstothe
cachedcopyismoreefficientthanaccesstotheoriginal.
Cachingandbufferingaretwodistinctfunctions,butsometimesaregionof
memorycanbeusedforbothpurposes.
10.2.3SpoolingandDeviceReservation
Aspoolisabufferthatholdsoutputforadevice,suchasaprinter,that
cannotacceptinterleaveddatastreams.Thespoolingsystemcopiesthe
queuedspoolfilestotheprinteroneatatime.
Insomeoperatingsystems,spoolingismanagedbyasystemdaemon
process.Inotheroperatingsystems,itishandledbyaninkernelthread.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

45/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

10.2.4ErrorHandling
Anoperatingsystemthatusesprotectedmemorycanguardagainstmany
kindsofhardwareandapplicationerrors.

10.3Devicedrivers
Incomputing,adevicedriverorsoftwaredriverisacomputerprogram
allowinghigherlevelcomputerprogramstointeractwithahardwaredevice.
Adrivertypicallycommunicateswiththedevicethroughthecomputerbus
orcommunicationssubsystemtowhichthehardwareconnects.Whena
callingprograminvokesaroutineinthedriver,thedriverissuescommands
tothedevice.
Oncethedevicesendsdatabacktothedriver,thedrivermayinvoke
routinesintheoriginalcallingprogram.Driversarehardwaredependentand
operatingsystemspecific.
Theyusuallyprovidetheinterrupthandlingrequiredforanynecessary
asynchronoustimedependenthardwareinterface.

10.4Summary
Thesystemcallinterfaceprovidedtoapplicationsisdesignedtohandle
severalbasiccategoriesofhardware,includingblockdevices,characterdevices,
memorymappedfiles,networksockets,andprogrammedintervaltimers.The
systemcallsusuallyblocktheprocessesthatissuethem,butnonblockingand
asynchronouscallsareusedbythekernelitselfandbyapplicationsthatmustnot
sleepwhilewaitingforanI/Ooperationtocomplete.
Thekernel'sI/Osubsystemprovidesnumerousservices.AmongtheseareI/O
scheduling,buffering,caching.Spooling,devicereservation,anderrorhandling.
I/OsystemcallsarecostlyintermsofCPUconsumptionbecauseofthemany
layersofsoftwarebetweenaphysicaldeviceandanapplication.

10.5ModelQuestion
Q.1ExplainapplicationofI/Ointerface?
Q.2DescribeblockingandnonblockingI/O?
Q.3Explainfollowingconcepts
a)ClockandTimers
b)DeviceDrivers
Q.4Writeashortnoteson
a)Scheduling
b)Buffering
c)ErrorHandling
Q.5Explainspoolingmechanism?
Q.6ExplainCachingindetails?

CHAPTER11
SECONDARYSTORADEMANAGEMENT
UnitStructure
11.0Objectives
11.1DiskStructure
11.2DiskScheduling
11.3DiskManagement
11.4SwapSpaceManagement
11.5DiskReliability
11.6StableStorageImplementation
11.7Summary
11.8ModelQuestion

11.0Objective
Describethephysicalstructureofsecondaryandtertiarystoragedevicesand
theresultingeffectsontheusesofthedevices.
Explaintheperformancecharacteristicsofmassstoragedevices.
Discussoperatingsystemservicesprovidedformassstorage.

11.1DiskStructure
Diskprovidebulkofsecondarystorageofcomputersystem.Thediskcanbe
consideredtheoneI/Odevicethatiscommontoeachandeverycomputer.
Diskscomeinmanysizeandspeeds,andinformationmaybestored
opticallyormagnetically.Magnetictapewasusedasanearlysecondary
storagemedium,buttheaccesstimeismuchslowerthanfordisks.For
backup,tapesarecurrentlyused.
Moderndiskdrivesareaddressedaslargeonedimensionalarraysoflogical
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

46/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

blocks,wherethelogicalblockisthesmallestunitoftransfer.Theactual
detailsofdiskI/Ooperationdependsonthecomputersystem,theoperating
systemandthenatureoftheI/Ochannelanddiskcontrollerhardware.
Thebasicunitofinformationstorageisasector.Thesectorsarestoredona
flat,circular,mediadisk.Thismediaspinsclosetooneormoreread/write
heads.Theheadscanmovefromtheinnerportionofthedisktotheouter
portion.
Whenthediskdriveisoperating,thediskisrotatingatconstantspeed.To
readorwrite,theheadmustbepositionedatthedesiredtrackandatthe
beginningofthedesiredsectoronthattrack.Trackselectioninvolves
movingtheheadinamovableheadsystemorelectronicallyselectingone
headonafixedheadsystem.Thesecharacteristicsarecommontofloppy
disks,harddisks,CDROMandDVD.

11.2DiskPerformanceParameters
Whenthediskdriveisoperating,thediskisrotatingatconstantspeed.To
readorwrite,theheadmustbepositionedatthedesiredtrackandatthe
beginningofthedesiredsectoronthattrack.
Trackselectioninvolvesmovingtheheadinamovableheadsystemor
electronicallyselectingoneheadonafixedheadsystem.Onamovablehead
system,thetimeittakestopositiontheheadatthetrackisknownas
seektime.
Whenoncethetrackisselected,thediskcontrollerwaitsuntilthe
appropriatesectorrotatestolineupwiththehead.Thetimeittakesforthe
beginningofthesectortoreachtheheadisknownasrotationaldelay,or
rotationallatency.Thesumoftheseektime,ifany,andtherotationaldelay
equalstheaccesstime,whichisthetimeittakestogetintopositiontoread
orwrite.
Oncetheheadisinposition,thereadorwriteoperationisthenperformedas
thesectormovesundertheheadthisisthedatatransferportionofthe
operationthetimerequiredforthetransferisthetransfertime.
SeekTimeSeektimeisthetimerequiredtomovethediskarmtothe
requiredtrack.Itturnsoutthatthisisadifficultquantitytopindown.The
seektimeconsistsoftwokeycomponents:theinitialstartuptimeandthe
timetakentotraversethetracksthathavetobecrossedoncetheaccessarm
isuptospeed.
Ts=mxn+s
RotationalDelayDisks,otherthanfloppydisks,rotateatspeedsranging
from3600rpmupto,asofthiswriting,15,000rpmatthislatterspeed,
thereisonerevolutionper4ms.Thus,ontheaverage,therotationaldelay
willbe2ms.Floppydiskstypicallyrotateatbetween300and600rpm.
Thustheaveragedelaywillbebetween100and50ms.
TransferTimeThetransfertimetoorfromthediskdependsontherotation
speedofthediskinthefollowingfashion:
T=b/rN
where
T=transfertime
b=numberofbytestobetransferred
N=numberofbytesonatrack
r=rotationspeed,inrevolutionspersecond
Thusthetotalaverageaccesstimecanbeexpressedas
Ta=Ts+
whereTsistheaverageseektime.

11.3DiskScheduling
TheamountofheadneededtosatisfyaseriesofI/Orequestcanaffectthe
performance.Ifdesireddiskdriveandcontrollerareavailable,therequest
canbeservicedimmediately.Ifadeviceorcontrollerisbusy,anynew
requestsforservicewillbeplacedonthequeueofpendingrequestsforthat
drive.Whenonerequestiscompleted,theoperatingsystemchooseswhich
pendingrequesttoservicenext.
Differenttypesofschedulingalgorithmsareasfollows.
1.FirstCome,FirstServedschedulingalgorithm(FCFS).
2.ShortestSeekTimeFirst(SSTF)algorithm
3.SCANalgorithm
4.CircularSCAN(CSCAN)algorithm
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

47/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

5.LookSchedulingAlgorithm
11.3.1FirstCome,FirstServedschedulingalgorithm(FCFS).
Thesimplestformofschedulingisfirstinfirstout(FIFO)scheduling,
whichprocessesitemsfromthequeueinsequentialorder.Thisstrategyhas
theadvantageofbeingfair,becauseeveryrequestishonoredandthe
requestsarehonoredintheorderreceived.WithFIFO,ifthereareonlya
fewprocessesthatrequireaccessandifmanyoftherequestsaretoclustered
filesectors,thenwecanhopeforgoodperformance.
PriorityWithasystembasedonpriority(PRI),thecontrolofthescheduling
isoutsidethecontrolofdiskmanagementsoftware.
LastInFirstOutlntransactionprocessingsystems,givingthedevicetothe
mostrecentusershouldresult.Inlittleornoarmmovementformoving
throughasequentialfile.Takingadvantageofthislocalityimproves
throughputandreducesqueuelength.
11.3.2ShortestSeekTimeFirst(SSTF)algorithm
TheSSTFpolicyistoselectthediskI/Orequesttherequirestheleast
movementofthediskarmfromitscurrentposition.ScanWiththeexception
ofFIFO,allofthepoliciesdescribedsofarcanleavesomerequest
unfulfilleduntiltheentirequeueisemptied.Thatis,theremayalwaysbe
newrequestsarrivingthatwillbechosenbeforeanexistingrequest.
ThechoiceshouldprovidebetterperformancethanFCFSalgorithm.
Underheavyload,SSTFcanpreventdistantrequestfromeverbeing
serviced.Thisphenomenonisknownasstarvation.SSTFschedulingis
essentiallyafromofshortestjobfirstscheduling.SSTFscheduling
algorithmarenotverypopularbecauseoftworeasons.
1.Starvationpossiblyexists.
2.itincreaseshigheroverheads.
11.3.3SCANschedulingalgorithm
Thescanalgorithmhastheheadstartattrack0andmovetowardsthe
highestnumberedtrack,servicingallrequestsforatrackasitpassesthe
track.Theservicedirectionisthenreservedandthescanproceedsinthe
oppositedirection,againpickingupallrequestsinorder.
SCANalgorithmisguaranteedtoserviceeveryrequestinonecompletepass
throughthedisk.SCANalgorithmbehavesalmostidenticallywiththeSSTF
algorithm.TheSCANalgorithmissometimescalledelevatoralgorithm.
11.3.4CSCANSchedulingAlgorithm
TheCSCANpolicyrestrictsscanningtoonedirectiononly.Thus,whenthe
lasttrackhasbeenvisitedinonedirection,thearmisreturnedtothe
oppositeendofthediskandthescanbeginsagain.
Thisreducesthemaximumdelayexperiencedbynewrequests.
11.3.5LOOKSchedulingAlgorithm
Starttheheadmovinginonedirection.Satisfytherequestfortheclosest
trackinthatdirectionwhenthereisnomorerequestinthedirection,the
headistraveling,reversedirectionandrepeat.Thisalgorithmissimilarto
innermostandoutermosttrackoneachcircuit.

11.4DiskManagement
Operatingsystemisresponsiblefordiskmanagement.Followingaresome
activitiesdiscussed.
11.4.1DiskFormatting
Diskformattingisoftwotypes.
a)Physicalformattingorlowlevelformatting.
b)LogicalFormatting
PhysicalFormatting
Diskmustbeformattedbeforestoringdata.
Diskmustbedividedintosectorsthatthediskcontrollerscanread/write.
Lowlevelformattingfilesthediskwithaspecialdatastructureforeach
sector.
Datastructureconsistsofthreefields:header,dataareaandtrailer.
Headerandtrailercontaininformationusedbythediskcontroller.
SectornumberandErrorCorrectingCodes(ECC)containedintheheader
andtrailer.
ForwritingdatatothesectorECCisupdated.
ForreadingdatafromthesectorECCisrecalculated.
Lowlevelformattingisdoneatfactory.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

48/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

LogicalFormatting
Afterdiskispartitioned,logicalformattingused.
Operatingsystemstorestheinitialfilesystemdatastructuresontothedisk.
11.4.2BootBlock
Whenacomputersystemispowereduporrebooted,aprograminreadonly
memoryexecutes.
Diagnosticcheckisdonefirst.
Stage0bootprogramisexecuted.
Bootprogramreadsthefirstsectorfromthebootdeviceandcontainsa
stage1bootprogram.
Maybebootsectorwillnotcontainabootprogram.
PCbootingfromharddisk,thebootsectoralsocontainsapartitiontable.
ThecodeinthebootROMinstructsthediskcontrollertoreadtheboot
blocksintomemoryandthenstartsexecutingthatcode.
Fullbootstrapprogramismoresophisticatedthanthebootstraploaderinthe
bootROM.

11.5SwapSpaceManagement
Swapspacemanagementislowleveltaskoftheoperatingsystem.Themain
goalforthedesignandimplementationofswapspaceistoprovidethebest
throughputforthevirtualmemorysystem.
11.5.1SwapSpaceUse
Theoperatingsystemneedstoreleasesufficientmainmemorytobringina
process
thatisreadytoexecute.Operatingsystemusesthisswapspaceinvariousway.
Pagingsystemsmaysimplystorepagesthathavebeenpushedoutofmain
memory.Unixoperatingsystemallowstheuseofmultipleswapspaceare
usually
putonseparatedisks,sotheloadplacedontheI/Osystembypagingand
swapping
canbespreadoverthesystemsI/Odevices.
11.5.2SwapSpaceLocation
Swapspacecanresideintwoplaces:
1.Separatediskpartition
2.NormalfileSystem
Iftheswapspaceissimplyalargefilewithinthefilesystem,normalfile
systemroutinescanbeusedtocreateit,nameitandallocateitsspace.This
iseasytoimplementbutalsoinefficient.Externalfragmentationcangreatly
increaseswappingtimes.Catchingisusedtoimprovethesystem
performance.Blockofinformationiscachedinthephysicalmemory,andby
usingspecialtoolstoallocatephysicallycontinuousblocksfortheswapfile.
Swapspacecanbecreatedinaseparatediskpartition.Nofilesystemor
directorystructureisplacedonthisspace.Aseparateswapspacestorage
managerisusedtoallocateanddeallocatetheblocks.Thismanageruses
algorithmsoptimizedforspeed.Internalfragmentationmayincrease.Some
operatingsystemsareflexibleandcanswapbothinrawpartitionsandinfile
systemspace.

11.6StableStorageImplementation
Thewriteaheadlog,whichrequiredtheavailabilityofstablestorage.
Bydefinition,informationresidinginstablestorageisneverlost.
Toimplementsuchstorage,weneedtoreplicatetherequiredinformationon
multiplestoragedevices(usuallydisks)withindependentfailuremodes.
Wealsoneedtocoordinatethewritingofupdatesinawaythatguarantees
thatafailureduringanupdatewillnotleaveallthecopiesinadamaged
stateandthat,whenwearerecoveringfromfailure,wecanforceallcopies
toaconsistentandcorrectvalue,evenifanotherfailureoccursduringthe
recovery.

11.6DiskReliability
Goodperformancemeanshighspeed,anotherimportantaspectof
performanceisreliability.
Afixeddiskdriveislikelytobemorereliablethanaremovablediskortape
drive.
Anopticalcartridgeislikelytobemorereliablethanamagneticdiskor
tape.
Aheadcrashinafixedharddiskgenerallydestroysthedata,whereasthe
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

49/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

failureofatapedriveoropticaldiskdriveoftenleavesthedatacartridge
unharmed.

11.7Summary
DiskdrivesarethemajorsecondarystorageI/Odevicesonmostcomputers.
Mostsecondarydevicesareeithermagneticdisksormagnetictapes.Modern
disk
drivesarestructuredaslargeonedimensionalarraysoflogicaldiskblocks.Disk
schedulingalgorithmscanimprovetheeffectivebandwidth,theaverage
response
time,andthevarianceresponsetime.AlgorithmssuchasSSTF,SCAN,C
SCAN.
LOOK,andCLOOKaredesignedtomakesuchimprovementsthrough
strategies
fordiskqueueordering.
Performancecanbeharmedbyexternalfragmentation.Theoperating
systemmanagesblock.First,adiskmustbelowlevelformattedtocreatethe
sectorsontherawhardware,newdisksusuallycomepreformatted.Then,diskis
partitioned,filesystemsarecreated,andbootblocksareallocatedtostorethe
systembootstrapprogram.Finallywhenablockiscorrupted,thesystemmust
have
awaytolockoutthatblockortoreplaceitlogicallywithaspace.
Becauseofefficientswapspaceisakeytogoodperformance,systems
usuallybypassthefilesystemanduserawdiskaccessforpagingI/O.Some
systemsdedicatearawdiskpartitiontoswapspace,andothersuseafilewithin
thefilesysteminstead.

11.8ModelQuestion
Q.1Explaindiskstructure?
Q.2Explainfollowingschedulingalgorithms:
1.FirstCome,FirstServedschedulingalgorithm(FCFS).
2.ShortestSeekTimeFirst(SSTF)algorithm
3.SCANalgorithm
4.CircularSCAN(CSCAN)algorithm
5.LookSchedulingAlgorithm
Q.3Explainswapspacemanagement?
Q.4ExplainDiskmanagementandtypes?
Q.5Describediskreliability?

CHAPTER12
FILESYSTEMS
UnitStructure
12.0Objectives
12.1FileConcept
12.2FileSupport
12.3AccessMethods
12.4DirectorySystems
12.5FileProtection
12.6FreeSpaceManagement
12.7Summary
12.8ModelQuestion

12.0Objective
Toexplainthefunctionoffilesystems.
Todescribetheinterfacestothefilesystems.
Todiscussfilesystemdesigntradeoffs,includingaccessmethods,file
sharing,filelocking,anddirectorystructure.
Toexplorefilesystemprotection.

12.1FileConcept
Afileisacollectionofsimilarrecords.Thefileistreatedasasingleentity
by
usersandapplicationsandmaybereferredbyname.Fileshaveuniquefile
namesandmaybecreatedanddeleted.Restrictionsonaccesscontrolusually
applyatthefilelevel.
Afileisacontainerforacollectionofinformation.Thefilemanager
providesa
protectionmechanismtoallowusersadministratorhowprocessesexecutingon
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

50/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

behalfofdifferentuserscanaccesstheinformationinafile.Fileprotectionisa
fundamentalpropertyoffilesbecauseitallowsdifferentpeopletostoretheir
informationonasharedcomputer.
Filerepresentsprogramsanddata.Datafilesmaybenumeric,alphabetic,
binaryoralphanumeric.Filesmaybefreeform,suchastextfiles.Ingeneral,
fileissequenceofbits,bytes,linesorrecords.
Afilehasacertaindefinedstructureaccordingtoitstype.
1TextFile
2SourceFile
3ExecutableFile
4ObjectFile
FileStructure
Fourtermsareuseforfiles
Field
Record
Database
Afieldisthebasicelementofdata.Anindividualfieldcontainsasingle
value.Arecordisacollectionofrelatedfieldsthatcanbetreatedasaunitby
some
applicationprogram.
Afileisacollectionofsimilarrecords.Thefileistreatedasasinglyentity
byusersandapplicationsandmaybereferencedbyname.Fileshavefilenames
andmaybecreatedanddeleted.Accesscontrolrestrictionsusuallyapplyatthe
file
level.
Adatabaseisacollectionofrelateddata.Databaseisdesignedforusebya
numberofdifferentapplications.Adatabasemaycontainalloftheinformation
relatedtoanorganizationorproject,suchasabusinessorascientificstudy.The
databaseitselfconsistsofoneormoretypesoffiles.Usually,thereisaseparate
databasemanagementsystemthatisindependentoftheoperatingsystem.
FileAttributes
Fileattributesvaryfromoneoperatingsystemtoanother.Thecommon
attributesare,
Nameonlyinformationkeptinhumanreadableform.
Identifieruniquetag(number)identifiesfilewithinfilesystem
Typeneededforsystemsthatsupportdifferenttypes
Locationpointertofilelocationondevice
Sizecurrentfilesize
Protectioncontrolswhocandoreading,writing,executing
Time,date,anduseridentificationdataforprotection,security,and
usagemonitoring
Informationaboutfilesarekeptinthedirectorystructure,whichis
maintainedonthedisk
FileOperations
Anyfilesystemprovidesnotonlyameanstostoredataorganizedasfiles,
butacollectionoffunctionsthatcanbeperformedonfiles.Typicaloperations
includethefollowing:
Create:Anewfileisdefinedandpositionedwithinthestructureoffiles.
Delete:Afileisremovedfromthefilestructureanddestroyed.
Open:Anexistingfileisdeclaredtobe"opened"byaprocess,allowingthe
processtoperformfunctionsonthefile.
Close:Thefileisclosedwithrespecttoaprocess,sothattheprocessnolonger
mayperformfunctionsonthefile,untiltheprocessopensthefileagain.
Read:Aprocessreadsalloraportionofthedatainafile.
Write:Aprocessupdatesafile,eitherbyaddingnewdatathatexpandsthesize
of
thefileorbychangingthevaluesofexistingdataitemsinthefile.
FileTypesName,Extension
Acommontechniqueforimplementingfiletypesistoincludethetypeas
partofthefilename.Thenameissplitintotwoparts:anameandan
extension.Followingtablegivesthefiletypewithusualextensionand
function.
FileTypeUsualExtensionFunction
Executableexe,com,binReadtorunmachine
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

51/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

languageprogram.
Objectobj,oCompiled,machine
language,notlinked
SourceCodec,cc,java,pasasm,aSourcecodeinvarious
language
Texttxt,docTextualdata,documents
FileManagementSystems:
Afilemanagementsystemisthatsetofsystemsoftwarethatprovidesservices
to
usersandapplicationsintheuseoffiles.followingobjectivesforafile
managementsystem:
Tomeetthedatamanagementneedsandrequirementsoftheuserwhich
include
storageofdataandtheabilitytoperformtheaforementionedoperations.
Toguarantee,totheextentpossible,thatthedatainthefilearevalid.
Tooptimizeperformance,bothfromthesystempointofviewintermsof
overall
throughput.
ToprovideI/Osupportforavarietyofstoragedevicetypes.
Tominimizeoreliminatethepotentialforlostordestroyeddata.
ToprovideastandardizedsetofI/Ointerfaceroutinestouseprocesses.
TOprovideI/Osupportformultipleusers,inthecaseofmultipleuser
systemsFileSystemArchitecture.Atthelowestlevel,devicedrivers
communicatedirectlywithperipheraldevicesortheircontrollersorchannels.A
devicedriverisresponsibleforstartingI/Ooperationsonadeviceand
processing
thecompletionofanI/Orequest.Forfileoperations,thetypicaldevices
controlled
arediskandtapedrives.Devicedriversareusuallyconsideredtobepartofthe
operatingsystem.
TheI/Ocontrol,consistsofdevicedriversandinterrupthandlerstotransfer
informationbetweenthememoryandthedisksystem.Adevicedrivercanbe
thoughtofasatranslator.
Thebasicfilesystemneedsonlytoissuegenericcommandstothe
appropriatedevicedrivertoreadandwritephysicalblocksonthedisk.
Thefileorganizationmoduleknowsaboutfilesandtheirlogicalblocks,as
wellasphysicalblocks.Byknowingthetypeoffileallocationusedandthe
locationofthefile,thefileorganizationmodulecantranslatelogicalblock
addressestophysicalblockaddressesforthebasicfilesystemtotransfer.Each
file'slogicalblocksarenumberedfrom0(or1)throughN,whereasthephysical
blockscontainingthedatausuallydonotmatchthelogicalnumbers,soa
translationisneededtolocateeachblock.Thefileorganizationmodulealso
includesthefreespacemanager,whichtracksunallocatedandprovidesthese
blockstothefileorganizationmodulewhenrequested.
Thelogicalfilesystemusesthedirectorystructuretoprovidethe
fileorganization
modulewiththeinformationthelatterneeds,givenasymbolicfile
name.Thelogicalfilesystemisalsoresponsibleforprotectionandsecurity.
Tocreateanewfile,anapplicationprogramcallsthelogicalfilesystem.
Thelogicalfilesystemknowstheformatofthedirectorystructures.Tocreatea
newfile,itreadstheappropriatedirectoryintomemory,updatesitwiththenew
entry,andwritesitbacktothedisk.
Oncethefileisfoundtheassociatedinformationsuchassize,owner,access
permissionsanddatablocklocationsaregenerallycopiedintoatablein
memory,
referredtoastheopenfilefable,consistingofinformationaboutallthe
currently
openedfiles.
Thefirstreferencetoafile(normallyanopen)causesthedirectorystructure
tobesearchedandthedirectoryentryforthisfiletobecopiedintothetableof
openedfiles.Theindexintothistableisreturnedtotheuserprogram,andall
furtherreferencesaremadethroughtheindexratherthanwithasymbolicname.
Thenamegiventotheindexvaries.Unixsystemsrefertoitasafiledescriptor,
Windows/NTasafilehandle,andothersystemsasafilecontrolblock.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

52/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Consequently,aslongasthefileisnotclosed,allfileoperationsaredoneon
theopenfiletable.Whenthefileisclosedbyallusersthathaveopenedit,the
updatedfileinformationiscopiedbacktothediskbaseddirectorystructure.
FileSystemMounting
Asafilemustbeopenedbeforeitisused,afilesystemmustbemounted
beforeitcanbeavailabletoprocessesonthesystem.Themountprocedure
isstraightforward.Thestemisgiventhenameofthedevice,andthe
locationwithinthefilestructureatwhichtoattachthefilesystem(calledthe
mountpoint).
Theoperatingsystemverifiesthatthedevicecontainsavalidfilesystem.It
doessobyaskingthedevicedrivertoreadthedevicedirectoryandverifying
thatthedirectoryhastheexpectedformat.Finally,theoperatingsystem
notesinitsdirectorystructurethatafilesystemismountedatthespecified
mountpoint.Thisschemeenablestheoperatingsystemtotraverseits
directorystructure,switchingamongfilesystemsasappropriate.
AllocationMethods
Thedirectaccessnatureofdisksallowsusflexibilityintheimplementation
offiles.Threemajormethodsofallocatingdiskspaceareinwideuse:
contiguous,linkedandindexed.Eachmethodhasitsadvantagesand
disadvantages.
ContiguousAllocation
Thecontiguousallocationmethodrequireseachfiletooccupyasetof
contiguousblocksonthedisk.Diskaddressesdefinealinearorderingonthe
disk.Noticethatwiththisorderingassumingthatonlyonejobisaccessing
thedisk,accessingblockb+1afterblockbnormallyrequiresnohead
movement.
Whenheadmovementisneeded,itisonlyonetrack.Thus,thenumberof
diskseeksrequiredforaccessingcontiguouslyallocatedfilesisminimal.
Contiguousallocationofafileisdefinedbythediskaddressandlength(in
blockunits)ofthefirstblock.Ifthefileisnblockslong,andstartsat
location!),thenitoccupiesblocksb,b+1,b+2,...,b+n1.Thedirectory
entryforeachfileindicatestheaddressofthestartingblockandthelength
oftheareaallocateforthisfile.
Accessingafilethathasbeenallocatedcontiguouslyiseasy.Forsequential
access,thefilesystemremembersthediskaddressofthelastblock
referencedand,whennecessary,readsthenextblock.Fordirectaccessto
blockiofafilethatstartsatblockb,wecanimmediatelyaccessblockb+i.
Thecontiguousdiskspaceallocationproblemcanbeseentobeaparticular
applicationofthegeneraldynamicstorageallocationFirstFitandBestFit
arethemostcommonstrategiesusedtoselectafreeholefromthesetof
availableholes.Simulationshaveshownthatbothfirstfitandbestfitare
moreefficientthanworstfitintermsofbothtimeandstorageutilization.
Neitherfirstfitnorbestfitisclearlybestintermsofstorageutilization,but
firstfitisgenerallyfaster.
Thesealgorithmssufferfromtheproblemofexternalfragmentation.Asfiles
areallocatedanddeleted,thefreediskspaceisbrokenintolittlepieces.
Externalfragmentationexistswheneverfreespaceisbrokenintochunks.It
becomesaproblemwhenthelargestcontiguouschunksisinsufficientfora
requeststorageisfragmentedintoanumberofholes,nooneofwhichis
largeenoughtostorethedata.Dependingonthetotalamountofdiskstorage
andtheaveragefilesize,externalfragmentationmaybeeitheraminorora
majorproblem.
Topreventlossofsignificantamountsofdiskspacetoexternal
fragmentation,theuserhadtorunrepackingroutinethatcopiedtheentire
filesystemontoanotherfloppydiskorontoatape.Theoriginalfloppydisk
wasthenfreedcompletely,creatingonelargecontiguousfreespace.The
routinethencopiedthefilesbackontothefloppydiskbyallocating
contiguousspacefromthisonelargehole.Thisschemeeffectivelycompacts
allfreespaceintoonecontiguousspace,solvingthefragmentationproblem.
Thecostofthiscompactionistime.
Thetimecostisparticularlysevereforlargeharddisksthatusecontiguous
allocation,wherecompactingallthespacemaytakehoursandmaybe
necessaryonaweeklybasis.Duringthisdowntime,normalsystem
operationgenerallycannotbepermitted,sosuchcompactionisavoidedat
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

53/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

allcostsonproductionmachines.
Amajorproblemisdetermininghowmuchspaceisneededforafile.When
thefileiscreated,thetotalamountofspaceitwillneedmustbefoundand
allocated.
Theuserwillnormallyoverestimatetheamountofspaceneeded,resulting
inconsiderablewastedspace.
LinkedAllocation
Linkedallocationsolvesallproblemsofcontiguousallocation.Withlink
allocation,eachfileisalinkedlistdiskblocksthediskblocksmaybe
scatteredanywhereonthedisk.
Thispointerisinitializedtonil(theendoflistpointervalue)tosignifyan
emptyfile.Thesizefieldisalsosetto0.Awritetothefilecausesafreebio
tobefoundviathefreespacemanagementsystem,andthisnewblockisthe
writtento,andislinkedtotheendofthefile
Thereisnoexternalfragmentationwithlinkedallocation,andanyfree!
blockonthefreespacelistcanbeusedtosatisfyarequest.Noticealsothat
thereisnoneedtodeclarethesizeofafilewhenthatfileiscreated.Afile
cancontinuetogrowaslongastherearefreeblocks.Consequently,itis
nevernecessarytocompactdiskspace.
Themajorproblemisthatitcanbeusedeffectivelyforonlysequential
accessfiles.Tofindtheithblockofafilewemuststartatthebeginningof
thatfile,andfollowthepointersuntilwegettotheithblock.Eachaccessto
apointerrequiresadiskreadandsometimesadiskseek.Consequently,itis
inefficienttosupportadirectaccesscapabilityforlinkedallocationfiles.
LinkedallocationisthespacerequiredforthepointersIfapointerrequires4
bytesoutofa512Byteblockthen0.78percentofthediskisbeingusedfor
pointer,ratherthanforinformation.
Theusualsolutiontothisproblemistocollectblocksintomultiples,called
clusters,andtoallocatetheclustersratherthanblocks.Forinstance,thefile
systemdefineaclusteras4blocksandoperateonthediskinonlycluster
units.
Pointersthenuseamuchsmallerpercentageofthefile'sdiskspace.This
methodallowsthelogicaltophysicalblockmappingtoremainsimple,but
improvesdiskthroughput(fewerdiskheadseeks)anddecreasesthespace
neededforblockallocationandfreelistmanagement.Thecostofthis
approachanincreaseininternalfragmentation.
Yetanotherproblemisreliability.Sincethefilesarelinkedtogetherby
pointersscatteredalloverthedisk,considerwhatwouldhappenifa
pointerwerelostordamaged.Partialsolutionsaretousedoublylinked
listsortostorethefilenameandrelativeblocknumberineachblock
however,theseschemesrequireevenmoreoverheadforeachfile.
Animportantvariation,onthelinkedallocationmethodistheuseofafile
allocationtable(FAT).Thissimplebutefficientmethodofdiskspace
allocationisusedbytheMSDOSandOS/2operatingsystems.Asectionof
diskatthebeginningofeachpartitionissetasidetocontainthetable.The
tablehasoneentryforeachdiskblock,andisindexedbyblocknumber.The
FATisusedmuchasisalinkedlist.Thedirectoryentrycontainstheblock
numberofthefirstblockofthefile.Thetableentryindexedbythatblock
numberthencontainstheblocknumberofthenextblockinthefile.This
chaincontinuesuntilthelastblock,whichhasaspecialendoffilevalueas
thetableentry.Unusedblocksareindicatedbya0tablevalue.Allocatinga
newblocktoafileisasimplematteroffindingthefirst0valuedtableentry,
andreplacingthepreviousendoffilevaluewiththeaddressofthenew
block.The0isthenreplacedwiththeendoffilevalue.Anillustrative
exampleistheFATstructureofforafileconsistingofdiskblocks217,618,
and339.
IndexedAllocation
Linkedallocationsolvestheexternalfragmentationandsizedeclaration
problemsofcontiguousallocation.TheabsenceofaFAT,linkedallocation
cannotsupportefficientdirectaccess,sincethepointerstotheblocksare
scatteredwiththeblocksthemselvesalloverthediskandneedtobe
retrievedinorderIndexedallocationsolvesthisproblembybringingallthe
pointerstogetherintoonelocation:theindexblock.
Eachfilehasitsownindexblock,whichisanarrayofdiskblockaddresses.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

54/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Theithentryintheindexblockpointstotheithblockofthefile.The
directorycontainstheaddressoftheindexblock.
Whenthefileiscreated,allpointersintheindexblockaresettonil.When
theithblockisfirstwritten,ablockisobtained:fromthefreespacemanager,
anditsaddressisputintheithindexblockentry.
Allocationsupportsdirectaccess,withoutsufferingfromexternal
fragmentationbecauseanyfreeblockonhediskmaysatisfyarequestfor
morespace.
Indexedallocationdoessufferfromwastedspace.Thepointeroverheadof
theindexblockisgenerallygreaterthanthepointeroverheadoflinked
allocation.
1.Linkedscheme.Anindexblockisnormallyonediskblock.Thus,it
canbereadandwrittendirectlybyitself.
2.Multilevelindex.Avariantofthelinkedrepresentationistousea
firstlevelindexblocktopointtoasetofsecondlevelindexblocks,
whichinturnpointtothefileblocks.Toaccessablock,theoperating
systemusesthefirstlevelindextofindasecondlevelindexblock,
andthatblocktofindthedesireddatablock.
FreeSpaceManagement
Sincethereisonlyalimitedamountofdiskspace,itisnecessarytoreusethe
space
fromdeletedfilesfornewfiles,ifpossible.
BitVector
Freespacelistisimplementedasabitmaporbitvector.Eachblockis
representedby1bit.Iftheblockisfree,thebitis1iftheblockisallocated,
thebitis0.
Forexampleconsideradiskwhereblocks2,3,4,5,8,9,10,11,12,13,17,
18,25,26,and27arefree,andtherestoftheblocksareallocated.Thefreespace
bitmapwouldbe
001111001111110001100000011100000..
Themainadvantageofthisapproachisthatitisrelativelysimpleand
efficienttofindthefirstfreeblockornconsecutivefreeblocksonthedisk.
Thecalculationoftheblocknumberis
(numberofbitsperword)x(numberof0valuewords)+offsetoffirst1bit
LinkedList
Anotherapproachistolinktogetherallthefreediskblocks,keepinga
pointytothefirstfreeblockinaspeciallocationonthediskandcachingit
inmemory.Thisfirstblockcontainsapointertothenextfreediskblock,
andsoon.Block2wouldcontainapointertoblock3,whichwouldpointto
block4,whichwouldpointtoblock5,whichwouldpointtoblock8,andso
on.Usually,theoperatingsystemsimplyneedsafreeblocksothatitcan
allocatethatblocktoafile,sothefirstblockinthefreelistisused.
Grouping
Amodificationofthefreelistapproachistostoretheaddressesofnfree
blocksinthefirstfreeblock.Thefirstn1oftheseblocksareactuallyfree.
Theimportanceofthisimplementationisthattheaddressesofalarge
numberoffreeblockscanbefoundquickly,unlikeinthestandardlinkedlist
approach.
Counting
Severalcontiguousblocksmaybeallocatedorfreedsimultaneously,
particularlywhenspaceisallocatedwiththecontiguousallocationalgorithm
orthroughclustering.Alistofnfreediskaddresses,wecankeepthe
addressofthefirstfreeblockandthenumbernoffreecontiguousblocks
thatfollowthefirstblock.
Eachentryinthefreespacelistthenconsistsofadiskaddressandacount.
Althougheachentryrequiresmorespacethanwouldasimplediskaddress,
theoveralllistwillbeshorter,aslongascountisgenerallygreaterthan1.

14.9Summary
Afileisanabstractdatatypedefinedandimplementedbytheoperating
system.Itisasequenceoflogicalrecords.Alogicalrecordmaybeabyte,a
line,
oramorecomplexdataitem.Theoperatingsystemmayspecificallysupport
variousrecordtypesormayleavethatsupporttotheapplicationprogram.
Themajortaskfortheoperatingsystemistomapthelogicalfileconcept
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

55/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

ontophysicalstoragedevicessuchasmagnetictapeordisk.Allthefile
informationkeptinthedirectorystructure.Filesystemisimplementedonthe
disk
andmemory.
Diskaddressdefinealinearaddressingonthedisk.Continuousallocation
algorithmsuffersfromtheexternalfragmentation.Freespacemanagement
techniquesarebitvector,linkedlist.Grouping,counting.
Sincefilearethemaininformationstoragemechanisminmostcomputer
systems,fileprotectionisneeded.Accesstofilescanbecontrolledseparately
for
eachtypeofaccessread,write,execute,append,delete,listdirectory,andso
on.
Fileprotectioncanbeprovidedbyaccesslists,passwords,orothertechniques.

14.10ModelQuestion
Q.1Explainthefileconcept?
Q.2Listthedifferenttypesoffiles?
Q.3Describethedifferenttypesofaccessmethods?
Q.4Whataretheadvantagesanddisadvantagesofcontinuous,linkedand
indexedallocationmethods?
Q.5Explainthefilesystemstructure?
Q.6Whataredifferenttypesofpartitionsandmounting?

CHAPTER13
PROTECTION
UnitStructure
13.0Objectives
13.1GoalsofProtection
13.2DomainofProtection
13.3AccessMatrix
13.4RevocationofAccessRights
13.5Summary
13.6ModelQuestion

13.0Objective
Discussthegoalsandprinciplesofprotectioninamoderncomputersystem.
Explainhowprotectiondomainscombinedwithanaccessmatrixareusedto
specifytheresourcesaprocessmayaccess.
Examinecapabilityandlanguagebasedprotectionsystems

13.1GoalsofProtection
Protectioncanimprovereliabilitybydetectinglatenterrorsattheinterfaces
betweencomponentsubsystems.Earlydetectionofinterfaceerrorscanoften
preventcontaminationofahealthysubsystembyamalfunctioningsubsystem.
Also,anunprotectedresourcecannotdefendagainstusebyanunauthorizedor
incompetentuser.Aprotectionorientedsystemprovidesmeanstodistinguish
betweenauthorizedandunauthorizedusage.
Theroleofprotectioninacomputersystemistoprovideamechanismforthe
enforcementofthepoliciesgoverningresourceuse.Thesepoliciescanbe
establishedinavarietyofways.Somearefixedinthedesignofthesystem,
while
othersareformulatedbythemanagementofasystem.Stillothersaredefinedby
theindividualuserstoprotecttheirownfilesandprograms.Aprotectionsystem
musthavetheflexibilitytoenforceavarietyofpolicies.Theapplication
programmerneedstouseprotectionmechanism.

13.2PrinciplesofProtection
Frequently,aguidingprinciplecanbeusedthroughoutaproject,suchasthe
designofanoperatingsystem.Followingthisprinciplesimplifiesdesign
decisionsandkeepsthesystemconsistentandeasytounderstand.Akey,
timetestedguidingprincipleforprotectionistheprincipleofleastprivilege.
Itdictatesthatprograms,users,andevensystemsbegivenjustenough
privilegestoperformtheirtasks.
Anoperatingsystemfollowingtheprincipleofleastprivilegeimplementsits
features,programs,systemcalls,anddatastructuressothatfailureor
compromiseofacomponentdoestheminimumdamageandallowsthe
minimumdamagetobedone.
Theprincipleofleastprivilegecanhelpproduceamoresecurecomputing
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

56/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

environment.

13.3DomainofProtection
Acomputersystemisacollectionofprocessesandobjects.Byobjects,we
meanbothhardwareobjects(suchastheCPU,memorysegments,printers,
disks,tapedrives),andsoftwareobjects(suchasfiles,programs,and
semaphore).
Protectiondomainisprocessthatoperateswithinaprotectiondomain,which
specifiestheresourcesthattheprocessmayaccess.Eachdomaindefinesa
setofobjectsand.thetypesofoperationsthatmaybeinvokedoneach
object.
Theabilitytoexecuteanoperationonanobjectisanaccessright.Adomain
isacollectionofaccess'rights,eachofwhichisanorderedpair<objectname,
rightsset>.Forexample,ifdomainDhastheaccessright<fileF,
{read,write}>,thenaprocessexecutingindomainDcanbothreadand
writefileF,ifcannot,however,performanyotheroperationonthatobject.
FigSystemwiththreeprotectiondomains.
Domainsdonotneedtobedisjointtheymayshareaccessrights.The
associationbetweenaprocessandadomainmaybeeitherstaticordynamic.
Adomaincanberealizedinavarietyofways:
1.Eachusermaybeadomain.Thesetofobjectsthatcanbeaccesseddepends
ontheidentityoftheuser.Domainswitchingoccurwhentheuseris
changedgenerallywhenoneuserlogsoutandanotheruserlogsin.
2.Eachprocessmaybeadomain.Inthiscase,thesetofobjectsthatcanbe
accesseddependsontheidentityoftheprocess.Domainswitching
correspondstooneprocesssendingamessagetoanotherprocess,andthen
waitingforaresponse.
3.Eachproceduremaybeadomain.Inthiscase,thesetofobjectsthatcanbe
accessedcorrespondstothelocalvariablesdefineDomainswitchingoccurs
whenaprocedurecallismade.

13.3AccessMatrix
Ourmodelofprotectioncanbeviewedabstractlyasamatrix,calledan
accessmatrix.Therowsoftheaccessmatrixrepresentdomains,andthe
columnsrepresentobjects.Eachentryinthematrixconsistsofasetof
accessrights.
Becauseobjectsaredefinedexplicitlybythecolumn,wecanomittheobject
namefromtheaccessright.Theentryaccess(i,j)definesthesetof
operationsthataprocess,executingindomainDi,caninvokeonobjectOj.
WeconsidertheaccessmatrixshowninFigure.Therearefourdomainsand
fourobjects:threefiles(F1,F2,F3),andonelaserprinter.Whenaprocess
executesindomainD1,itcanreadfilesF1andF3..Aprocessexecutingin
domainD4hasthesameprivilegesasitdoesindomainD1,butinaddition,
itcanalsowriteontofilesF1andF3.Notethatthelaserprintercanbe
accessedonlybyaprocessexecutingindomainD2.
Theaccessmatrixschemeprovidesuswiththemechanismforspecifyinga
varietyofpolicies.Morespecifically,wemustensurethataprocess
executingindomainDicanaccessonlythoseobjectsspecifiedinrowi,and
thenonlyasallowedbytheaccessmatrixentries.
Object
Domain
F1F2F3printer
D1ReadRead
D2Print
D3readExecute
D4ReadwriteReadwrite
FigAccessMatrix
Policydecisionsconcerningprotectioncanbeimplementedbytheaccess
matrix.Theusersnormallydecidethecontentsoftheaccessmatrixentries.
Allowingcontrolledchangetothecontentsoftheaccessmatrixentries
requiresthreeadditionaloperations:copy,owner,andcontrol.
13.4RevocationofAccessRights
Inadynamicprotectionsystem,wemaysometimesneedtorevolveaccess
rightstoobjectssharedbydifferentusers.Variousquestionsaboutrevocation
may
arise:
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

57/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Immediateversusdelayed.Doesrevocationoccurimmediately,orisit
delayed?Ifrevocationisdelayed,canwefindoutwhenitwilltakeplace?
Selectiveversusgeneral.Whenanaccessrighttoanobjectrevoked,doesit
affectalltheuserswhohaveanaccessrighttothatobject,orcanwespecify
aselectgroupofuserswhoseaccessrightsshouldberevoked?
Partialversustotal.Canasubsetoftherightsassociatedwithanobjectbe
revoked,ormustwerevokeallaccessrightsforthisobject?
Temporaryversuspermanent.Canaccessberevokedpermanently(thatis,
therevokedaccessrightwillneveragainbeavailable),orcanaccessbe
revokedandlaterbeobtainedagain?
Schemesthatimplementsrevocationforcapabilitiesincludethefollowing:
Reacquisition.Periodically,capabilitiesaredeletedfromeachdomain.Ifa
processwantstouseacapability,itmayfindthatcapabilityhasbeen
deleted.Theprocessmaythentrytoreacquirethecapability.Ifaccesshas
beenrevoked,theprocesswillnotbeabletoreacquirethecapability.
Backpointers.Alistofpointersismaintainedwitheachobject,pointingto
allcapabilitiesassociatedwiththatobject.Whenrevocationisrequired,we
canfollowthispointers,changingthecapabilitiesasnecessary.Thisscheme
wasadoptedintheMULTICSsystem.
Indirection.Thecapabilitiespointindirectly,notdirectly,totheobjects.
Eachcapabilitypointstoauniqueentryinaglobaltrade,whichinturn
pointstotheobject.Weimplementrevocationbysearchingtheglobaltable
forthedesiredentryanddeletingit.Itdoesnotallowselectiverevocation.
Keys.Akeyisauniquebitpatternthatcanbeassociatedwithacapability.
Thiskeyisdefinedwhenthecapabilityiscreated,anditcanbeneither
modifier\ednorinspectedbytheprocessthatownsthecapability.Amaster
keyisassociatedwitheachobjectitcanbedefinedorreplacedwiththesetkey
operation.

13.5Summary
Computersystemcontainsmanyobjects,andtheyneedtobeprotectedfrom
misuse.Objectsmaybehardware(suchasmemory,CPUtime,andI/Odevices)
or
software(suchasfiles,programs,andsemaphores).Anaccessrightispermission
toperformanoperationonanobject.Adomainisasetofaccessrights.
Processes
executeindomainsandmayuseanyoftheaccessrightsinthedomaintoaccess
andmanipulateobjects.Duringitslifetime,aprocessmaybeeitherboundtoa
protectiondomainorallowedtoswitchfromonedomaintoanother.
Theaccessmatrixisageneralmodelofprotectionthatprovidesa
mechanismforprotectionwithoutimposingaparticularprotectionpolicyonthe
systemoritsusers.Theseparationofpolicyandmechanismisanimportant
design
policy.
Realsystemsaremuchmorelimitedthanthegeneralmodelandtendto
provideprotectionforfiles.

13.6ModelQuestion
Q.1DefineandexplainAccessmatrix?
Q.2Howdoesthesystemsthatimplementtheprincipleofleastprivilegestill
haveprotectionsystems?
Q.3Discussstrengthsandweaknessesofimplementinganaccessmatrixusing
accesslist?
Q.4ExplainDomainStructure?

CHAPTER14
SECURITY
UnitStructure
14.0Objectives
14.1Thesecurityproblem
14.2Authentication
14.3OneTimepasswords
14.4ProgramThreats
14.5SystemThreats
14.6ThreatMonitoring
14.7Encryption
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

58/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

14.8ComputerSecurityClassifications
14.9Summary
14.10ModelQuestion

14.0Objective
Todiscusssecuritythreatsandattacks.
Toexplainthefundamentalsofencryption,authentication,andhashing.
Toexaminetheusesofcryptographyincomputing.
Todescribethevariouscountermeasurestosecurityattacks.

14.1TheSecurityProblem
Theoperatingsystemcanallowuserstoprotecttheirresources.Wesaythat
asystemissecureifitsresourcesartusedandaccessedasintendedunderall
circumstances.Unfortunately,itisnotgenerallypossibletoachievetotal
security.
Securityviolationsofthesystemcanbecategorizedasbeingeitherintentional
(malicious)oraccidental.Amongtheformsofmaliciousaccessarethe
following:
Unauthorizedreadingofdata(theftofinformation).
Unauthorizedmodificationofdata.
Unauthorizeddestructionofdata.
Toprotectthesystem,wemusttakesecuritymeasuresattwolevels:
Physical:Thesiteorsitescontainingthecomputersystemsmustbephysically
securedagainstarmedorsurreptitiousentrybyintruders.
Human:Usersmustbescreenedcarefullysothatthechanceofauthorizinga
userwhothengivesaccesstoanintruder(inexchangeforabribe,forexample)
is
reduced.
Securityatbothlevelsmustbemaintainedifoperatingsystemsecurityisto
beensured.
Fig14.1StandardSecurityAttack.

14.2Authentication
Amajorsecurityproblemforoperatingsystemsistheauthenticationproblem.
The
protectionsystemdependsonanabilitytoidentifytheprogramsandprocesses
that
areexecuting.Authenticationisbasedononeormoreofthreeitems:user
possession(akeyorcard),userknowledge(auseridentifierandpassword),and
a
userattribute(fingerprint)retinapattern,orsignature).
Constrainingsetofpotentialsendersofamessage
Complementaryandsometimesredundanttoencryption.
Alsocanprovemessageunmodified.
Anauthenticationalgorithmconsistsoffollowingcomponents:
AsetKofkeys.
AsetMofmessages.
AsetAofauthenticators.
AfunctionS:K(MA)
Thatis,foreachkK,S(k)isafunctionforgeneratingauthenticators
frommessages.
BothSandS(k)foranykshouldbeefficientlycomputablefunctions.
AfunctionV:K(MA{true,false}).Thatis,foreachkK,V(k)isa
functionforverifyingauthenticatorsonmessages.
BothVandV(k)foranykshouldbeefficientlycomputablefunctions.
Foramessagem,acomputercangenerateanauthenticatoraAsuchthat
V(k)(m,a)=trueonlyifitpossessesS(k).
Thus,computerholdingS(k)cangenerateauthenticatorsonmessagesso
that
anyothercomputerpossessingV(k)canverifythem.
ComputernotholdingS(k)cannotgenerateauthenticatorsonmessagesthat
can
beverifiedusingV(k).
Sinceauthenticatorsaregenerallyexposed(forexample,theyaresenton
the
networkwiththemessagesthemselves),itmustnotbefeasibletoderiveS(k)
fromtheauthenticators.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

59/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

AuthenticationHashFunctions
Basisofauthentication.
Createssmall,fixedsizeblockofdata(messagedigest,hashvalue)from
m.
HashFunctionHmustbecollisionresistantonm
Mustbeinfeasibletofindanm'msuchthatH(m)=H(m').
IfH(m)=H(m'),thenm=m'
Themessagehasnotbeenmodified.
CommonmessagedigestfunctionsincludeMD5,whichproducesa128bit
hash,andSHA1,whichoutputsa160bithash.
AuthenticationMAC
Symmetricencryptionusedinmessageauthenticationcode(MAC)
authenticationalgorithm.
Simpleexample:
MACdefinesS(k)(m)=f(k,H(m)).
Wherefisafunctionthatisonewayonitsfirstargument.
kcannotbederivedfromf(k,H(m)).
Becauseofthecollisionresistanceinthehashfunction,reasonably
assurednoothermessagecouldcreatethesameMAC.
AsuitableverificationalgorithmisV(k)(m,a)(f(k,m)=a).
NotethatkisneededtocomputebothS(k)andV(k),soanyoneableto
computeonecancomputetheother.
AuthenticationDigitalSignature
Basedonasymmetrickeysanddigitalsignaturealgorithm.
Authenticatorsproducedaredigitalsignatures.
Inadigitalsignaturealgorithm,computationallyinfeasibletoderiveS(ks)
from
V(kv)
Visaonewayfunction.
Thus,kvisthepublickeyandksistheprivatekey.
ConsidertheRSAdigitalsignaturealgorithm.
SimilartotheRSAencryptionalgorithm,butthekeyuseisreversed
DigitalsignatureofmessageS(ks)(m)=H(m)ksmodN
Thekeyksagainisapaird,N,whereNistheproductoftwolarge,
randomlychosenprimenumberspandq.
VerificationalgorithmisV(kv)(m,a)(akvmodN=H(m))
Wherekvsatisfieskvksmod(p1)(q1)=1
Whyauthenticationifasubsetofencryption?
Fewercomputations(exceptforRSAdigitalsignatures).
Authenticatorusuallyshorterthanmessage.
ItCanbebasisfornonrepudiation.

14.3OneTimepasswords
Toavoidtheproblemsofpasswordsniffingandshouldersurfing,asystem
coulduseasetofpairedpasswords.Whenasessionbegins,thesystem
randomlyselectsandpresentsonepartofapasswordpairtheusermust
supplytheotherpart.Inthissystem,theuserischallengedandmustrespond
withthecorrectanswertothatchallenge.
Thisapproachcanbegeneralizedtotheuseofanalgorithmasapassword.
Thealgorithmmightbeanintegerfunction.
Inthisonetimepasswordsystem,thepasswordisdifferentineachinstance.
Anyonecapturingthepasswordfromonesessionandtryingtoreuseitin
anothersessionwillfail.
Theuserusesthekeypadtoenterthesharedsecret,alsoknownasapersonal
identificationnumber(PIN).Anothervariationononetimepasswordsisthe
useofacodebook,oronetimepad.

14.4ProgramThreats
Inanenvironmentwhereaprogramwrittenbyoneusermaybeusedby
anotheruser,thereisanopportunityformisuse,whichmayresultinunexpected
behavior.Therearetwocommonmethods.TrojanhorsesandTrapdoors.
14.4.1TrojanHorse
Manysystemshavemechanismsforallowingprogramswrittenbyusersto
beexecutedbyotherusers.Iftheseprogramsareexecutedinadomainthat
providestheaccessrightsoftheexecutinguser,theymaymisusethese
rights.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

60/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

AcodesegmentthatitsenvironmentiscalledaTrojanhorse.TheTrojanhorse
problemisexacerbatedbylongsearchpaths.Thesearchpathliststhe
setofdirectoriestosearchwhenanambiguousprogramnameisgiven.The
pathissearchedforafileofthatnameandthefileisexecuted.Allthe
directoriesinthesearchpathmustbesecure,oraTrojanhorsecouldbe
slippedintotheuser'spathandexecutedaccidentally.
AvariationoftheTrojanhorsewouldbeaprogramthatemulatesalogin
program.Theemulatorstoredawaythepassword,printedoutaloginerror
message,andexitedtheuserwasthenprovidedwithagenuinelogin
prompt.
Thistypeofattackcanbedefeatedbytheoperatingsystemprintingausage
messageattheendofaninteractivesessionorbyanontrappablekey
sequence,suchasthecontrolaltdeletecombinationthatWindowsNTuses.
14.4.2TrapDoor
Thedesignerofaprogramorsystemmightleaveaholeinthesoftwarethat
onlyOperatingSystemiscapableofusing.Aclevertrapdoorcouldbeincluded
in
acompiler.Thecompilercouldgeneratestandardobjectcodeaswellasatrap
door,regardlessofthesourcecodebeingcompiled.

14.5SystemThreats
Mostoperatingsystemsprovideameansforprocessestospawnotherprocesses.
14.5.1Worms
Awormisaprocessthatusesthespawnmechanismtoclobbersystem
performance.Thewormspawnscopiesofitself,usingupsystemresources
andperhapslockingoutsystemuseby,allotherprocesses.Sincetheymay
reproducethemselvesamongsystemsandthusshutdowntheentirenetwork.
Thewormwasmadeupoftwoprogramsagrapplinghook(alsocalled
bootstraporvector)programandthemainprogram.Thegrapplinghook
consistedof99linesofCcodecompiledandrunoneachmachineit
accessed.Thegrapplinghookconnectedtothemachinewhereitoriginated
anduploadedacopyofthemainwormontothe"hooked"system.Themain
programproceededtosearchforothermachinestowhichthenewlyinfected
systemcouldconnecteasily.
Theattackviaremoteaccesswasoneofthreeinfectionmethodsbuiltinto
theworm.
14.5.2Viruses
Anotherformofcomputerattackisavirus.Likeworms,virusesare
designedtospreadintootherprogramsandcanwreakhavocinasystem,
includingmodifyingordestroyingfilesandcausingsystemcrashesand
programmalfunctions.Whereasawormisstructuredasacomplete,
standaloneprogram,avirusisafragmentofcodeembeddedinalegitimate
program.Virusesareamajorproblemforcomputerusers,especiallyusers
ofmicrocomputersystems.
Evenifavirusdoesinfectaprogram,itspowersarelimitedbecauseother
aspectsofthesystemareprotectedinmultiuser.Singleusersystemshave
nosuchprotectionsand,asaresult,avirushasfreerun.
Virusesareusuallyspreadbyusersdownloadingviralprogramsfrompublic
bulletinboardsorexchangingfloppydiskscontaininganinfection.Thebest
protectionagainstcomputervirusesisprevention,orthepracticeofSafe
computing.

14.6ThreatMonitoring
Thesecurityofasystemcanbeimprovedbytwomanagementtechniques.
Oneisthreatmonitoring:Thesystemcancheckforsuspiciouspatternsof
activityinanattempttodetectasecurityviolation.
Anothertechniqueisanauditlog.Anauditlogsimplyrecordsthetime,
user,andtypeofallaccessestoanobject.Networkedcomputersaremuch
moresusceptibletosecurityattacksthanarestandalonesystems.
Onesolutionistheuseofafirewalltoseparatetrustedanduntrusted
systems.Afirewallisacomputerorrouterthatsitsbetweenthetrustedand
theuntrusted.Itlimitsnetworkaccessbetweenthetwosecuritydomains,
andmonitorsandlogsallconnections.Afirewallthereforemayneedto
allowhttptopass.

14.7Encryption
Encryptionisonecommonmethodofprotectinginformationtransmitted
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

61/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

overunreliablelinks.Thebasicmechanismworksasfollows.
1.Theinformation(text)isencrypted(encoded)fromitsinitialreadable
form(calledcleartext),toaninternalform(calledciphertext).This
internaltextform,althoughreadable,doesnotmakeanysense.
2.Theciphertextcanbestoredinareadablefile,ortransmittedover
unprotectedchannels.
3.Tomakesenseoftheciphertext,thereceivermustdecrypt(decode)it
backintocleartext.
Eveniftheencryptedinformationisaccessedbyanunauthorizedpersonor
program,itwillbeuselessunlessitcanbedecoded.
Encryptionalgorithmconsistsof
SetofKkeys.
SetofMMessages.
SetofCciphertexts(encryptedmessages).
AfunctionE:K(MC).Thatis,foreachkK,E(k)isafunctionfor
generatingciphertextsfrommessages.
BothEandE(k)foranykshouldbeefficientlycomputablefunctions.
AfunctionD:K(CM).Thatis,foreachkK,D(k)isafunctionfor
generatingmessagesfromciphertexts.
BothDandD(k)foranykshouldbeefficientlycomputablefunctions.
Anencryptionalgorithmmustprovidethisessentialproperty:Givena
ciphertextcC,acomputercancomputemsuchthatE(k)(m)=conlyifit
possessesD(k).
Thus,acomputerholdingD(k)candecryptciphertextstotheplaintextsused
toproducethem,butacomputernotholdingD(k)cannotdecrypt
ciphertexts.
Sinceciphertextsaregenerallyexposed(forexample,sentonthenetwork),
itis
importantthatitbeinfeasibletoderiveD(k)fromtheciphertexts.

14.8ComputerSecurityClassifications
TheU.S.DepartmentofDefenseoutlinesfourdivisionsofcomputer
security:A,B,C,andD.
DMinimalsecurity.
CProvidesdiscretionaryprotectionthroughauditing.DividedintoC1and
C2.C1identifiescooperatinguserswiththesamelevelofprotection.C2
allowsuserlevelaccesscontrol.
BAllthepropertiesofC,howevereachobjectmayhaveunique
sensitivitylabels.DividedintoB1,B2,andB3.
AUsesformaldesignandverificationtechniquestoensuresecurity.

14.9Summary
Protectionisaninternalproblem.Security,incontrast,mustconsiderboth
thecomputersystemandtheenvironmentpeople,buildings,businesses,
valuable
objects,andthreatswithinwhichthesystemisused.
Thedatastoredinthecomputersystemmustbeprotectedfromunauthorized
access,maliciousdestructionoralteration,andaccidentalintroductionof
inconsistency.Itiseasiertoprotectagainstaccidentallossofdataconsistency
than
toprotectagainstmaliciousaccesstothedata.
Severaltypesofattackscanbelaunchedagainstprogramsandagainst
individualcomputesorthemasses.Encryptionlimitsthedomainofreceiversof
data,whileauthenticationlimitsthedomainofsenders.Userauthentication
methodsareusedtoidentifylegitimateusersofasystem.

14.10ModelQuestion
Q.1DefineandexplainEncryption?
Q.2Explainauthenticationprocess?
Q.3Explainvarioustypesofsystemthreats?
Q.4Writeanoteonfollowing
a)viruses
b)ComputerSecuritySpecification
Q.5ExplaintypesofProgramthreats?

CHAPTER15
LINUXSYSTEM
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

62/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

UnitStructure
15.0Objectives
15.1LinuxintroductionandFileSystem
15.2BasicFeatures
15.3Advantages
15.4BasicArchitectureofUNIX/LinuxSystem
15.5Summary
15.6ModelQuestion

15.0Objective
ToexplorethehistoryoftheUNIXoperatingsystemfromwhichLinuxis
derivedandtheprincipleswhichLinuxisdesignedupon.
ToexaminetheLinuxprocessmodelandillustratehowLinuxschedules
processesandprovidesinterprocesscommunication.
ToexplorehowLinuximplementsfilesystemsandmanagesI/Odevices.

15.1LinuxintroductionandFileSystem
LinuxlookslikeUNIXsystem.LinuxisdevelopedbyLinuxTorvalds.
Linuxdevelopmentbeganin1991.Linuxsourcecodeisavailableforfreeonthe
internet.ThebasicLinuxsystemisstandardenvironmentforapplicationsand
user
programming.
15.1.1ComponentsofaLinuxSystem
AnyLinuxsystemconsistsofthreecomponents.
1.Kernel
2.Systemlibraries
3.Systemutilities
Kernel:
TheKernelisresponsibleformaintainingalltheimportantabstractionofthe
operatingsystem.Itincludesvirtualmemoryandprocesses.Kernelismost
importantcomponentoftheLinuxsystem.
Systemlibraries:
Itcontainsstandardsetoffunctionsthroughwhichapplicationcaninteract
withtheKernel.Systemlibraryimplementsmuchoftheoperatingsystem
functionalitythatdoesnotneedthefullprivilegesofKernelcode.
Systemutilities:
Systemutilitiesareprogramsthatperformindividual,specialized
managementtasks.
Fig.15.1showsthecomponentsoftheLinuxsystem.
AlltheKernelcodeexecutesintheprocessorsprivilegedmodewithfull
accesstoallthephysicalresourcesofthecomputer.Linuxreferstothis
privilegedmodeasKernelmode.InLinux,nousermodecodeisbuiltinto
theKernel.
System
Management
programs
User
Processes
Userutility
programs
Compilers
Systemsharedlibraries
LinuxKernel
LoadableKernelmodules
Fig.15.1ComponentsofLinuxsystem
AnyoperatingsystemsupportcodethatdoesnotneedtourninKernelmode
isplacedintothesystemlibrariesinstead.
TheKerneliscreatedasasingle,monolithicbinary.AllKernelcodeand
datastructuresarekeptinasingleaddressspace,nocontextswitchesare
necessarywhenaprocesscallsanoperatingsystemfunction.Core
scheduling,virtualmemorycodealsooccupiedsameaddressspace.
LinuxKernelprovidesallthefunctionalitynecessarytorunprocesses,andit
providessystemservicestogivearbitratedandprotectedaccesstohardware
resources
TheLinuxsystemincludesawidevarietyofusermodeprogramsboth
systemutilitiesanduserutilities.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

63/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

15.2KernelModules
KernelcodeexecutesinKernelmodewithfullaccesstoallthephysical
resourcesofthecomputer.SectionsofKernelcodethatcanbecompiled,
loadedandunloadedindependentoftherestoftheKernel.
AKernelmodulemaytypicallyimplementadevicedriver,afilesystem,or
anetworkingprotocol.Themoduleinterfaceallowsthirdpartiestowriteand
distribute,ontheirownteams,devicedriversorfilesystemsthatcouldnot
bedistributedundertheGPL.
TheloadableKernelmodulesruninprivilegedKernelmode.Kernel
modulesallowaLinuxsystemtobesetupwithastandard,minimalKernel,
withoutanyextradevicedriversbuiltin.Kernelmanagementallows
modulestobedynamicallyloadedintomemorywhenneeded.
LinuxKernelmoduleshasthreecomponent.
1.Modulemanagement
2.Driverregistration
3.Conflictresolutionmechanism
1.Modulemanagement
1.Itsupportloadingmodulesintomemoryandlettingthemtalktothe
restoftheKernel.
2.LinuxmaintainsaninternalsymboltableintheKernel.
3.Moduleloadingissplitintotwoseparatesections:
a.ManagingsectionsofmodulecodeinKernelmemory
b.Handlingsymbolsthatmodulesareallowedtoreference.
4.Symboltabledoesnotcontainthefullsetofsymboldefinedinthe
Kernelduringlattercompilation
5.Themodulerequestormanagesloadingrequested,butcurrently
unloadedmodules.
6.ItalsoregularlyqueriestheKerneltoseewhetheradynamically
loadedmoduleisstillinuseandwillunloaditwhenitisnolonger
activelyneeded
7.Originalservicerequestwillcompleteoncethemoduleisloaded.
2.DriverRegistration.
1.Allowsmodulestotelltherestofthekernelthatanewdriverhas
becomeavailable.
2.Kernelmaintainsdynamictablesofallknowndrivers.
3.Kernelalsoprovidesasetofroutinestoallowdriverstobeaddedor
removed.
4.Registrationtablecontainsfollowing:
a.Devicedrivers
b.Filesystems
c.Networkprotocols
d.Binaryformat.
5.Devicedriversmaybeblockorcharacterdevices.
6.Filessystemcontainsnetworkfilesystem,virtualfilesystemetc.
7.NetworkprotocolincludesIPX,packetfilteringrulesforanetwork.
3.ConflictResolution
1.Amechanismsthatallowsdifferentdevicedriverstoreservehardware
resourcesandtoprotectthoseresourcesfromaccidentaluseby
anotherdriver.
2.Linuxprovidesaventralconflictresolutionmechanism.
3.Conflictresolutionmoduleaimsare
a.Topreventmodulesfromclashingoveraccesstohardware
resources.
b.Preventautoprobesfrominterferingwithexistingdevice
drivers.
c.Resolveconflictsamongmultipledriverstryingtoaccessthe
samehardware.
4.Kernelmaintainslistsofallocatedhardwareresources.

15.3BasicFeatures
UNIXhasanumberoffeatures,mostlygoodandsomebad,butitisnecessary
to
knowatleastsomeofthem:
1.UNIXisPortable:Portabilityistheabilityofthesoftwarethatoperateson
one
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

64/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

machinetooperateonanother,differentmachine.InUNIXtherearetwotypes
of
portability,thatoftheUNIXoperatingsystemitself(i.e.theKernelprogram)
and
oftheapplicationprogram.
Advantagesofportabilityare:
a)Portableapplicationprogramdecreasetheprogrammingcosts.
b)Retrainingisavoidedastheenduserworksonasimilarsystemwith
enhanced
capabilities.
2.Opensystem:Thesystemthatmorethanonesystemcanaccessthesame
data
atthesametime.Severalpeopleinvolvedinacommonprojectcanconveniently
accesseachother'sdata.Apartfromdata,otherresourceslikememory(RAM),
the
CPU(thechip),ortheharddiskcanbeusedbymanyuserssimultaneously.
3.MultiuserCapability:Thismeansthatmorethanonesystemcanaccessthe
samedataatthesametime.Severalpeopleinvolvedinacommonprojectcan
convenientlyaccesseachother'sdata.Apartfromdata,otherresourceslike
memory(RAM),theCPU(thechip),ortheharddiskcanbeusedbymanyusers
simultaneously.
4.MultitaskingCapability:Multitaskingmeansthatausercanperformmore
thanonetasksatthesametime.Ausercandothisbyplacingsometasksinthe
backgroundwhileheworksonataskintheforeground.Anampersand(&)
placed
attheendofthecommandlinesendstheprocessinbackground.
5.HierarchicalFileSystem:Hierarchicalstructureoffersmaximumflexibility
for
groupinginformationinawaythatreflectsinnaturalstructure.Theprograms
and
datacanbeorganizedconvenientlysincefilescanbegroupedaccordingto
usage.
6.Theshell:UserinteractionwithUNIXiscontrolledbytheshell,apowerful
commandinterpreter.Theshellhasvariouscapabilitieslikeredirectingthe
applicationinputandoutputandalsotoprogressagroupoffileswithasingle
command.
7.UNIXhasbuiltinnetworking:TheUNIXhasvariousbuiltinprogramsand
utilitieslikeUUCP,mail,write,etc.Withtheseutilitiesonecancommunicate
with
otheruseroroneservertoanother.
8.Security:Computersystemsecuritymeansprotectinghardwareandthe
informationcontainedwithinthesystem.Securitymeanstoavoid:
a)Unauthorizedaccesstothecomputersystem.
b)Unauthorizedexaminationofoutput.
c)Unauthorizedtappingofdata.
d)Destructionofsoftwaredatabymistakeoronpurpose.
e)Examinationofsensitivedatabyunauthorizedusersandalterationof
sensitive
datawithoutdetection.
TheUNIXprovidesthefeatureslike:
a)Passwordprotectionforsystemaccess.
b)Controlaccesstoindividualfiles.
c)Encryptionofdatafiles.
9.SoftwareDevelopmentTools:UNIXoffersanexcellentvarietyoftoolsfor
softwaredevelopmentforallphases,fromprogrameditingtomaintenanceof
software.

15.4BasicArchitectureofUNIX/LinuxSystem
FigArchitectureofUNIXSystem
ThefigureshowsthearchitectureoftheUNIXsystemintheformofvarious
layers.Theinnermostlayeri.e.coreisthehardwareofthecomputersystem.
The
kernelisasoftwarewhichdirectlycomesincontactwiththehardwareand
controls
thehardware.Alayerabovethisistheshell.Abovethisthevariousutilitieslike
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

65/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Id
Kernel
HARDWAR
E

Shell
Id
vi
ed
grep
wc
date
a.out
CC
compilers
Application
Programs
USE
R
USE
R
USE
RUSE
R

nroff,troff,vi,as,etc.andthevariouscompilersandotherapplicationprogram
reside.Letusseetheselayersandtheirfunctionsindetail:
1.Hardware:Thehardwareatthecentreofthestructureprovidestheoperating
systemwithbasicservices.Thehardwareconstitutesalltheperipheralslike
memory(RAM,HDD,FDD,CDetc),processor,mouseandotherinputdevices,
terminal(i.e.VDUs),printersetc.
2.TheKernel:Theoperatingsysteminteractsdirectlywiththehardware,
providingcommonservicestoprogramsandinsulatinguserprogram
complexities
ofhardware.TheoperatingsystemisalsocalledasKernel.Thiskernelinteracts
directlywiththehardware.Becauseofthishardwareisolationofuserprogram,
itis
easytomovetheuserprogramseasilybetweenUNIXsystemsrunningon
different
hardware.
3.Shell:ShellisactuallytheinterfacebetweentheuserandtheKernelthat
isolates
theuserfromknowledgeofKernelfunctions.Theshellacceptsthecommands
keyedinbytheusersandchecksfortheirsyntaxandgivesouterrormessagesif
somethinggoes.Thesecommandaftergettinginterpretedbytheshellare
provided
tokernelforappropriateaction.Italsoprovidesthefeaturesofpipe(|)and
redirection(i.e.<,>,>>,<<).Theshellalsohasaprogrammingcapabilityofits
own.ThereareanumberofshellsavailableinvariousUNIXflavoursbut
common
area)
BourneShell(sh)
b)CShell(csh)
c)KornShell(ksh)
Theothershellsare:bash,restrictedShell(rsh)andvisualShell(vsh).The
bourneShell(sh)isalsocalledastandardshell.
4.UNIXutilities:TheUNIXsystemKerneldoesonlyleveljobsnecessaryto
scheduleprocesses,keeptrackoffiles,andcontrolhardwaredevices.
Allotheroperatingsystemfunctionsaredonebyutilityprogramswrittenas
softwaretools.
Followingaresomeoftheutilitiesthatplayaprominentroleintheoperatingof
the
UNIXsystem.
http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

66/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

a)Initinitializestheprocesscreationmechanism.
Foreachterminalwherealoginisallowed,initcreatesaprocessthatprintsthe
login:message.
b)Gettyprocessconditionstheconnectiontotheterminalsothatthe
terminalcancommunicatewiththecomputerandthenprintsthelogin:
message.
c)Loginwhenanuserrespondstotheloginprompttheloginprogramreplaces
getty.Iftheuseraccounthasapassword,loginprintsthepassword:
messageandcheckstoseethatthepasswordenterediscorrect.
Ifcorrect,programnamedinpasswordfile,usuallyBourneshellorC
shellreplacesloginandtheuserissuccessfullyloggedintothesystem.
d)sttychangesaterminalcharacteristics.
e)mkfsbuildsafilesystem.
f)mknodbuildsaspecialfilesystem.
g)mountunmountmountsandunmountsafilesystem.
h)synewritesadiskblockimagesfrommemorytodisk.

15.5Summary
Linuxisamodern,freeoperatingsystembasedonUNIXstandards.Ithas
designedtorunefficientlyandreliablyoncommonPChardwareitalsorunson
a
varietyofotherplatforms.Itprovideaprogramminginterfaceanduserinterface
compatiblewithstandardUNIXsystemsandcanrunalargenumberofUNIX
applications,includinganincreasingnumberofcommerciallysupported
applications.
LinuxhasnotevolvedinavacuumacompletelyLinuxsystemincludes
manycomponentsthatweredevelopedindependentlyofLinux.ThecoreLinux
operatingsystemkernelisentirelyoriginal,butallowsmuchexistingfreeUNIX
softwaretorun,resultinginaentireUNIXcompatibleoperatingsystemfree
from
proprietarycode.
TheLinuxkernelisimplementedasatraditionalmonolithickernelfor
performancereasons,butitismodularenoughindesigntoallowmostdriversto
be
dynamicallyloadedandunloadedatruntime.

15.6ModelQuestion
Q.1Listdifferentcomponentsofalinuxsystem?
Q.2WhatareKernelmodules?
Q.3ExplainBasicarchitectureofUNIX/Linuxsystem?
Q.4ExplainbasicfeaturesofUNIX/Linux?
Q.5DefineandexplainShell?
+3 Recommend this on Google

NewerPost

Home

OlderPost

0comments:
PostaComment

http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

67/68

1/17/2017

Operatingsystemforbcafullrefrence~BCANOTES

Enteryourcomment...

Commentas:

Publish

Unknown(Google)

Signout

Notifyme

Preview

Subscribeto:PostComments(Atom)

Copyright2017BCANOTES|PoweredbyBCANotes

http://bcaraipur.blogspot.in/2014/05/operatingsystemforbcafullrefrence.html

68/68

You might also like