Tải bản đầy đủ (.pdf) (1,847 trang)

Prentice hall operating systems design and implementation 3rd edition jan 2006 ISBN 0131429388

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.44 MB, 1,847 trang )




Tableof

Contents
• Index

OperatingSystemsDesignandImplementation,
ThirdEdition
ByAndrewS.Tanenbaum-VrijeUniversiteit
Amsterdam,TheNetherlands,AlbertS.WoodhullAmherst,Massachusetts
Publisher :PrenticeHall
PubDate :January04,2006
PrintISBN-10 :0-13-142938-8
PrintISBN-13 :978-0-13-142938-3
eTextISBN-10 :0-13-185991-9
eTextISBN-13 :978-0-13-185991-3
Pages :1080


RevisedtoaddressthelatestversionofMINIX(MINIX3),this
streamlined,simplifiedneweditionremainstheonlyoperating
systemstexttofirstexplainrelevantprinciples,thendemonstrate
theirapplicationsusingaUnix-likeoperatingsystemasadetailed
example.Ithasbeenespeciallydesignedforhighreliability,for
useinembeddedsystems,andforeaseofteaching.

ForthelatestversionofMINIXandsimulatorsforrunningMINIX
onothersystemsvisit:www.minix3.org






OperatingSystemsDesignandImplementation,
ThirdEdition
ByAndrewS.Tanenbaum-VrijeUniversiteit
Amsterdam,TheNetherlands,AlbertS.WoodhullAmherst,Massachusetts
Publisher :PrenticeHall
PubDate :January04,2006

PrintISBN-10 :0-13-142938-8
Tableof
PrintISBN-13 :978-0-13-142938-3

Contents
eTextISBN-10 :0-13-185991-9
• Index
eTextISBN-13 :978-0-13-185991-3
Pages :1080







































Copyright
Preface

Chapter1.Introduction
Section1.1.WhatIsanOperatingSystem?
Section1.2.HistoryofOperatingSystems
Section1.3.OperatingSystemConcepts
Section1.4.SystemCalls
Section1.5.OperatingSystemStructure
Section1.6.OutlineoftheRestofThisBook
Section1.7.Summary
Problems
Chapter2.Processes
Section2.1.IntroductiontoProcesses
Section2.2.InterprocessCommunication
Section2.3.ClassicalIPCProblems
Section2.4.Scheduling
Section2.5.OverviewofProcessesinMINIX3
Section2.6.ImplementationofProcessesinMINIX3
Section2.7.TheSystemTaskinMINIX3

xv
1
4
6
19
26
42
51
51
52
55
55

68
88
93
112
125
192















































































Section2.8.TheClockTaskinMINIX3
204
Section2.9.Summary
214
Problems
215
Chapter3.Input/Output

221
Section3.1.PrinciplesofI/OHardware
222
Section3.2.PrinciplesofI/OSoftware
229
Section3.3.Deadlocks
237
Section3.4.OverviewofI/OinMINIX3
252
Section3.5.BlockDevicesinMINIX3
261
Section3.6.RAMDisks
271
Section3.7.Disks
278
Section3.8.Terminals
302
Section3.9.Summary
366
Problems
367
Chapter4.MemoryManagement
373
Section4.1.BasicMemoryManagement
374
Section4.2.Swapping
378
Section4.3.VirtualMemory
383
Section4.4.PageReplacementAlgorithms

396
Section4.5.DesignIssuesforPagingSystems
404
Section4.6.Segmentation
410
Section4.7.OverviewoftheMINIX3ProcessManager
420
Section4.8.ImplementationoftheMINIX3ProcessManager 447
Section4.9.Summary
475
Problems
476
Chapter5.FileSystems
481
Section5.1.Files
482
Section5.2.Directories
491
Section5.3.FileSystemImplementation
497
Section5.4.Security
526
Section5.5.ProtectionMechanisms
537
Section5.6.OverviewoftheMINIX3FileSystem
548
Section5.7.ImplementationoftheMINIX3FileSystem
566
Section5.8.Summary
606

Problems
607
Chapter6.ReadingListandBibliography
611
Section6.1.SuggestionsforFurtherReading
611
Section6.2.AlphabeticalBibliography
618
AppendixA.InstallingMINIX3
629































SectionA.1.Preparation
SectionA.2.Booting
SectionA.3.InstallingtotheHardDisk
SectionA.4.Testing
SectionA.5.UsingaSimulator
AppendixB.TheMINIXSourceCode
AppendixC.IndextoFiles
AbouttheAuthors
AbouttheMINIX3CD
SystemRequirements
Hardware
Software
Installation
ProductSupport
Index

629
631
632
634

636
637
1033
1053
InsideBackCover
InsideBackCover
InsideBackCover
InsideBackCover
InsideBackCover
InsideBackCover


Copyright
[Pageiv]
LibraryofCongressCataloginginPublicationData

Tanenbaum,AndrewS.
OperatingSystems:DesignandImplementation/AndrewS.Tanenbaum,
-3rded.
ISBN:0-13-142938-8
1.Operatingsystems(Computers)I.Woodhull,AlbertS.II.Title

QA76.76.O63T362006
005.4'3--dc22
VicePresidentandEditorialDirector,ECS:MarciaJ.
Horton
ExecutiveEditor:TracyDunkelberger
EditorialAssistant:ChristiannaLee
ExecutiveManagingEditor:VinceO'Brien
ManagingEditor:CamilleTrentacoste

DirectorofCreativeServices:PaulBelfanti
ArtDirectorandCoverManager:HeatherScott
CoverDesignandIllutsration:TamaraNewnam


ManagingEditor,AVManagementandProduction:Patricia
Burns
ArtEditor:GregoryDulles
ManufacturingManager,ESM:AlexisHeydt-Long
ManufacturingBuyer:LisaMcDowell
ExecutiveMarketingManager:RobinO'Brien
MarketingAssistant:BarrieReinhold

©2006,1997,1987byPearsonEducation,Inc.
PearsonPrenticeHall
PearsonEducation,Inc.
UpperSaddleRiver,NJ07458
Allrightsreserved.Nopartofthisbookmaybereproducedin
anyformorbyanymeans,withoutpermissioninwritingfrom
thepublisher.
PearsonPrenticeHall®isatrademarkofPearsonEducation,
Inc.
Theauthorsandpublisherofthisbookhaveusedtheirbest
effortsinpreparingthisbook.Theseeffortsincludethe
development,research,andtestingofthetheoriesand
programstodeterminetheireffectiveness.Theauthorsand
publishermakenowarrantyofanykind,expressedorimplied,
withregardtotheseprogramsortothedocumentation
containedinthisbook.Theauthorsandpublishershallnotbe
liableinanyeventforincidentalorconsequentialdamagesin

connectionwith,orarisingoutof,thefurnishing,performance,
oruseoftheseprograms.


Allrightsreserved.Nopartofthisbookmaybereproduced,in
anyformorbyanymeans,withoutpermissioninwritingfrom
thepublisher.
PrintedintheUnitedStatesofAmerica
10987654321
PearsonEducationLtd.,London
PearsonEducationAustraliaPty.Ltd.,Sydney
PearsonEducationSingapore,Pte.Ltd.
PearsonEducationNorthAsiaLtd.,HongKong
PearsonEducationCanada,Inc.,Toronto
PearsonEducacióndeMexico,S.A.deC.V.
PearsonEducation-Japan,Tokyo
PearsonEducationMalaysia,Pte.Ltd.
PearsonEducation,Inc.,UpperSaddleRiver,NewJersey

Dedication
ToSuzanne,Barbara,Marvin,andthememoryofSweetie
pandBram
AST
ToBarbaraandGordon
ASW

TheMINIX3Mascot
Otheroperatingsystemshaveananimalmascot,sowefelt



MINIX3oughttohaveonetoo.Wechosetheraccoonbecause
raccoonsaresmall,cute,clever,agile,eatbugs,andareuserfriendlyatleastifyoukeepyourgarbagecanwelllocked.




[Pagexv]


Preface
Mostbooksonoperatingsystemsarestrongontheoryand
weakonpractice.Thisoneaimstoprovideabetterbalance
betweenthetwo.Itcoversallthefundamentalprinciplesin
greatdetail,includingprocesses,interprocesscommunication,
semaphores,monitors,messagepassing,scheduling
algorithms,input/output,deadlocks,devicedrivers,memory
management,pagingalgorithms,filesystemdesign,security,
andprotectionmechanisms.Butitalsodiscussesoneparticular
systemMINIX3aUNIX-compatibleoperatingsystemindetail,
andevenprovidesasourcecodelistingforstudy.This
arrangementallowsthereadernotonlytolearntheprinciples,
butalsotoseehowtheyareappliedinarealoperatingsystem.
Whenthefirsteditionofthisbookappearedin1987,itcaused
somethingofasmallrevolutioninthewayoperatingsystems
coursesweretaught.Untilthen,mostcoursesjustcovered
theory.WiththeappearanceofMINIX,manyschoolsbeganto
havelaboratorycoursesinwhichstudentsexaminedareal
operatingsystemtoseehowitworkedinside.Weconsiderthis
trendhighlydesirableandhopeitcontinues.
Ititsfirst10years,MINIXunderwentmanychanges.The

originalcodewasdesignedfora256K8088-basedIBMPCwith
twodiskettedrivesandnoharddisk.ItwasalsobasedonUNIX
Version7Astimewenton,MINIXevolvedinmanyways:it
supported32-bitprotectedmodemachineswithlargememories
andharddisks.ItalsochangedfrombeingbasedonVersion7,
tobeingbasedontheinternationalPOSIXstandard(IEEE
1003.1andISO9945-1).Finally,manynewfeatureswere
added,perhapstoomanyinourview,buttoofewintheviewof
someotherpeople,whichledtothecreationofLinux.In
addition,MINIXwasportedtomanyotherplatforms,including
theMacintosh,Amiga,Atari,andSPARC.Asecondeditionofthe


book,coveringthissystem,waspublishedin1997andwas
widelyusedatuniversities.

[Pagexvi]
ThepopularityofMINIXhascontinued,ascanbeobservedby
examiningthenumberofhitsforMINIXfoundbyGoogle.
Thisthirdeditionofthebookhasmanychangesthroughout.
Nearlyallofthematerialonprincipleshasbeenrevised,and
considerablenewmaterialhasbeenadded.However,themain
changeisthediscussionofthenewversionofthesystem,
calledMINIX3.andtheinclusionofthenewcodeinthisbook.
AlthoughlooselybasedonMINIX2,MINIX3isfundamentally
differentinmanykeyways.
ThedesignofMINIX3wasinspiredbytheobservationthat
operatingsystemsarebecomingbloated,slow,andunreliable.
Theycrashfarmoreoftenthanotherelectronicdevicessuchas
televisions,cellphones,andDVDplayersandhavesomany

featuresandoptionsthatpracticallynobodycanunderstand
themfullyormanagethemwell.Andofcourse,computer
viruses,worms,spyware,spam,andotherformsofmalware
havebecomeepidemic.
Toalargeextent,manyoftheseproblemsarecausedbya
fundamentaldesignflawincurrentoperatingsystems:their
lackofmodularity.Theentireoperatngsystemistypically
millionsoflinesofC/C++codecompiledintoasinglemassive
executableprogramruninkernelmode.Abuginanyoneof
thosemillionsoflinesofcodecancausethesystemto
malfunction.Gettingallthiscodecorrectisimpossible,
especiallywhenabout70%consistsofdevicedrivers,written
bythirdparties,andoutsidethepurviewofthepeople
maintainingtheoperatingsystem.
WithMINIX3,wedemonstratethatthismonolithicdesignisnot


theonlypossibility.TheMINIX3kernelisonlyabout4000lines
ofexecutablecode,notthemillionsfoundinWindows,Linux,
MacOSX,orFreeBSD.Therestofthesystem,includingallthe
devicedrivers(excepttheclockdriver),isacollectionofsmall,
modular,user-modeprocesses,eachofwhichistightly
restrictedinwhatitcandoandwithwhichotherprocessesit
maycommunicate.
WhileMINIX3isaworkinprogress,webelievethatthismodel
ofbuildinganoperatingsystemasacollectionofhighlyencapsulateduser-modeprocessesholdspromiseforbuilding
morereliablesystemsinthefuture.MINIX3isespecially
focusedonsmallerPCs(suchasthosecommonlyfoundin
Third-Worldcountriesandonembeddedsystems,whichare
alwaysresourceconstrained).Inanyevent,thisdesignmakes

itmucheasierforstudentstolearnhowanoperatingsystem
worksthanattemptingtostudyahugemonolithicsystem.
TheCD-ROMthatisincludedinthisbookisaliveCD.Youcan
putitinyourCD-ROMdrive,rebootthecomputer,andMINIX3
willgivealoginpromptwithinafewseconds.Youcanloginas
rootandgivethesystematrywithoutfirsthavingtoinstallit
onyourharddisk.Ofcourse,itcanalsobeinstalledonthehard
disk.DetailedinstallationinstructionsaregiveninAppendixA.

[Pagexvii]
Assuggestedabove,MINIX3israpidlyevolving,withnew
versionsbeingissuedfrequently.TodownloadthecurrentCDROMimagefileforburning,pleasegototheofficialWebsite:
www.minix3.org.Thissitealsocontainsalargeamountofnew
software,documentation,andnewsaboutMINIX3
development.FordiscussionsaboutMINIX3,ortoask
questions,thereisaUSENETnewsgroup:comp.os.minix.
PeoplewithoutnewsreaderscanfollowdiscussionsontheWeb
at />

AsanalternativetoinstallingMINIX3onyourharddisk,itis
possibletorunitonanyoneofseveralPCsimulatorsnow
available.Someofthesearelistedonthemainpageofthe
Website.
Instructorswhoareusingthebookasthetextforauniversity
coursecangettheproblemsolutionsfromtheirlocalPrentice
Hallrepresentative.ThebookhasitsownWebsite.Itcanbe
foundbygoingtowww.prenhall.com/tanenbaumandselecting
thistitle.
Wehavebeenextremelyfortunateinhavingthehelpofmany
peopleduringthecourseofthisproject.Firstandforemost,Ben

GrasandJorritHerderhavedonemostoftheprogrammingof
thenewversion.Theydidagreatjobundertighttime
constraints,includingrespondingtoe-mailwellaftermidnight
onmanyoccasions.Theyalsoreadthemanuscriptandmade
manyusefulcomments.Ourdeepestappreciationtobothof
them.
KeesBotalsohelpedgreatlywithpreviousversions,givingusa
goodbasetoworkwith.Keeswrotelargechunksofcodefor
versionsupto2.0.4,repairedbugs,andanswerednumerous
questions.PhilipHomburgwrotemostofthenetworkingcode
aswellashelpingoutinnumerousotherusefulways,especially
providingdetailedfeedbackonthemanuscript.
Peopletoonumeroustolistcontributedcodetotheveryearly
versions,helpingtogetMINIXoffthegroundinthefirstplace.
Thereweresomanyofthemandtheircontributionshavebeen
sovariedthatwecannotevenbegintolistthemallhere,sothe
bestwecandoisagenericthankyoutoallofthem.
Severalpeoplereadpartsofthemanuscriptandmade
suggestions.WewouldliketogiveourspecialthankstoGojko
Babic,MichaelCrowley,JosephM.Kizza,SamKohnAlexander
Manov,andDuZhangfortheirhelp.


Finally,wewouldliketothankourfamilies.Suzannehasbeen
throughthis16timesnow.Barbarahasbeenthroughit15
timesnow.Marvinhasbeenthroughit14timesnow.It'skind
ofgettingtoberoutine,buttheloveandsupportisstillmuch
appreciated.(AST)
Al'sBarbarahasbeenthroughthistwicenow.Hersupport,
patience,andgoodhumorwereessential.Gordonhasbeena

patientlistener.Itisstilladelighttohaveasonwho
understandsandcaresaboutthethingsthatfascinateme.
Finally,step-grandsonZain'sfirstbirthdaycoincideswiththe
releaseofMINIX3.Somedayhewillappreciatethis.(ASW)
AndrewS.Tanenbaum
AlbertS.Woodhull


[Page1]


1.Introduction
Withoutitssoftware,acomputerisbasicallyauselesslumpof
metal.Withitssoftware,acomputercanstore,process,and
retrieveinformation;playmusicandvideos;sende-mail,
searchtheInternet;andengageinmanyothervaluable
activitiestoearnitskeep.Computersoftwarecanbedivided
roughlyintotwokinds:systemprograms,whichmanagethe
operationofthecomputeritself,andapplicationprograms,
whichperformtheactualworktheuserwants.Themost
fundamentalsystemprogramistheoperatingsystem,whose
jobistocontrolallthecomputer'sresourcesandprovideabase
uponwhichtheapplicationprogramscanbewritten.Operating
systemsarethetopicofthisbook.Inparticular,anoperating
systemcalledMINIX3isusedasamodel,toillustratedesign
principlesandtherealitiesofimplementingadesign.
Amoderncomputersystemconsistsofoneormoreprocessors,
somemainmemory,disks,printers,akeyboard,adisplay,
networkinterfaces,andotherinput/outputdevices.Allinall,a
complexsystem.Writingprogramsthatkeeptrackofallthese

componentsandusethemcorrectly,letaloneoptimally,isan
extremelydifficultjob.Ifeveryprogrammerhadtobe
concernedwithhowdiskdriveswork,andwithallthedozensof
thingsthatcouldgowrongwhenreadingadiskblock,itis
unlikelythatmanyprogramscouldbewrittenatall.
Manyyearsagoitbecameabundantlyclearthatsomewayhad
tobefoundtoshieldprogrammersfromthecomplexityofthe
hardware.Thewaythathasevolvedgraduallyistoputalayer
ofsoftwareontopofthebarehardware,tomanageallpartsof
thesystem,andpresenttheuserwithaninterfaceorvirtual
machinethatiseasiertounderstandandprogram.Thislayer
ofsoftwareistheoperatingsystem.


[Page2]
TheplacementoftheoperatingsystemisshowninFig.1-1.At
thebottomisthehardware,which,inmanycases,isitself
composedoftwoormorelevels(orlayers).Thelowestlevel
containsphysicaldevices,consistingofintegratedcircuitchips,
wires,powersupplies,cathoderaytubes,andsimilarphysical
devices.Howtheseareconstructedandhowtheyworkisthe
provinceoftheelectricalengineer.

Figure1-1.Acomputersystemconsistsof
hardware,systemprograms,andapplication
programs.

Nextcomesthemicroarchitecturelevel,inwhichthephysical
devicesaregroupedtogethertoformfunctionalunits.Typically
thislevelcontainssomeregistersinternaltotheCPU(Central

ProcessingUnit)andadatapathcontaininganarithmeticlogic
unit.Ineachclockcycle,oneortwooperandsarefetchedfrom
theregistersandcombinedinthearithmeticlogicunit(for
example,byadditionorBooleanAND).Theresultisstoredin


oneormoreregisters.Onsomemachines,theoperationofthe
datapathiscontrolledbysoftware,calledthemicroprogram.
Onothermachines,itiscontrolleddirectlybyhardwarecircuits.
Thepurposeofthedatapathistoexecutesomesetof
instructions.Someofthesecanbecarriedoutinonedatapath
cycle;othersmayrequiremultipledatapathcycles.These
instructionsmayuseregistersorotherhardwarefacilities.
Together,thehardwareandinstructionsvisibletoanassembly
languageprogrammerformtheISA(InstructionSet
Architecture)Thislevelisoftencalledmachinelanguage.
Themachinelanguagetypicallyhasbetween50and300
instructions,mostlyformovingdataaroundthemachine,doing
arithmetic,andcomparingvalues.Inthislevel,theinput/output
devicesarecontrolledbyloadingvaluesintospecialdevice
registers.Forexample,adiskcanbecommandedtoreadby
loadingthevaluesofthediskaddress,mainmemoryaddress,
bytecount,anddirection(readorwrite)intoitsregisters.In
practice,manymoreparametersareneeded,andthestatus
returnedbythedriveafteranoperationmaybecomplex.
Furthermore,formanyI/O(Input/Output)devices,timingplays
animportantroleintheprogramming.

[Page3]
Amajorfunctionoftheoperatingsystemistohideallthis

complexityandgivetheprogrammeramoreconvenientsetof
instructionstoworkwith.Forexample,readblockfromfileis
conceptuallymuchsimplerthanhavingtoworryaboutthe
detailsofmovingdiskheads,waitingforthemtosettledown,
andsoon.
Ontopoftheoperatingsystemistherestofthesystem
software.Herewefindthecommandinterpreter(shell),window
systems,compilers,editors,andsimilarapplicationindependentprograms.Itisimportanttorealizethatthese


programsaredefinitelynotpartoftheoperatingsystem,even
thoughtheyaretypicallysuppliedpreinstalledbythecomputer
manufacturer,orinapackagewiththeoperatingsystemifitis
installedafterpurchase.Thisisacrucial,butsubtle,point.The
operatingsystemis(usually)thatportionofthesoftwarethat
runsinkernelmodeorsupervisormode.Itisprotectedfrom
usertamperingbythehardware(ignoringforthemomentsome
olderorlow-endmicroprocessorsthatdonothavehardware
protectionatall).Compilersandeditorsruninusermode.Ifa
userdoesnotlikeaparticularcompiler,he[ ]isfreetowritehis
ownifhesochooses;heisnotfreetowritehisownclock
interrupthandler,whichispartoftheoperatingsystemandis
normallyprotectedbyhardwareagainstattemptsbyusersto
modifyit.
[ ]"He"shouldbereadas"heorshe"throughoutthebook.

Thisdistinction,however,issometimesblurredinembedded
systems(whichmaynothavekernelmode)orinterpreted
systems(suchasJava-basedsystemsthatuseinterpretation,
nothardware,toseparatethecomponents).Still,fortraditional

computers,theoperatingsystemiswhatrunsinkernelmode.
Thatsaid,inmanysystemsthereareprogramsthatruninuser
modebutwhichhelptheoperatingsystemorperform
privilegedfunctions.Forexample,thereisoftenaprogramthat
allowsuserstochangetheirpasswords.Thisprogramisnot
partoftheoperatingsystemanddoesnotruninkernelmode,
butitclearlycarriesoutasensitivefunctionandhastobe
protectedinaspecialway.
Insomesystems,includingMINIX3,thisideaiscarriedtoan
extremeform,andpiecesofwhatistraditionallyconsideredto
betheoperatingsystem(suchasthefilesystem)runinuser
space.Insuchsystems,itisdifficulttodrawaclearboundary.
Everythingrunninginkernelmodeisclearlypartofthe
operatingsystem,butsomeprogramsrunningoutsideitare


arguablyalsopartofit,oratleastcloselyassociatedwithit.For
example,inMINIX3,thefilesystemissimplyabigCprogram
runninginuser-mode.
Finally,abovethesystemprogramscometheapplication
programs.Theseprogramsarepurchased(orwrittenby)the
userstosolvetheirparticularproblems,suchasword
processing,spreadsheets,engineeringcalculations,orstoring
informationinadatabase.


[Page4]

1.1.WhatIsanOperatingSystem?
Mostcomputerusershavehadsomeexperiencewithan

operatingsystem,butitisdifficulttopindownpreciselywhat
anoperatingsystemis.Partoftheproblemisthatoperating
systemsperformtwobasicallyunrelatedfunctions,extending
themachineandmanagingresources,anddependingonwhois
doingthetalking,youhearmostlyaboutonefunctionorthe
other.Letusnowlookatboth.

1.1.1.TheOperatingSystemasanExtended
Machine
Asmentionedearlier,thearchitecture(instructionset,
memoryorganization,I/O,andbusstructure)ofmost
computersatthemachinelanguagelevelisprimitiveand
awkwardtoprogram,especiallyforinput/output.Tomakethis
pointmoreconcrete,letusbrieflylookathowfloppydiskI/Ois
doneusingtheNECPD765compatiblecontrollerchipsusedon
manyIntel-basedpersonalcomputers.(Throughoutthisbook
wewillusetheterms"floppydisk"and"diskette"
interchangeably.)ThePD765has16commands,eachspecified
byloadingbetween1and9bytesintoadeviceregister.These
commandsareforreadingandwritingdata,movingthedisk
arm,andformattingtracks,aswellasinitializing,sensing,
resetting,andrecalibratingthecontrollerandthedrives.
Themostbasiccommandsarereadandwrite,eachofwhich
requires13parameters,packedinto9bytes.Theseparameters
specifysuchitemsastheaddressofthediskblocktoberead,
thenumberofsectorspertrack,therecordingmodeusedon
thephysicalmedium,theintersectorgapspacing,andwhatto


dowithadeleted-data-address-mark.Ifyoudonotunderstand

thismumbojumbo,donotworry;thatispreciselythepointitis
ratheresoteric.Whentheoperationiscompleted,thecontroller
chipreturns23statusanderrorfieldspackedinto7bytes.Asif
thiswerenotenough,thefloppydiskprogrammermustalsobe
constantlyawareofwhetherthemotorisonoroff.Ifthemotor
isoff,itmustbeturnedon(withalongstartupdelay)before
datacanbereadorwritten.Themotorcannotbeleftontoo
long,however,orthefloppydiskwillwearout.Theprogrammer
isthusforcedtodealwiththetrade-offbetweenlongstartup
delaysversuswearingoutfloppydisks(andlosingthedataon
them).
Withoutgoingintotherealdetails,itshouldbeclearthatthe
averageprogrammerprobablydoesnotwanttogettoo
intimatelyinvolvedwiththeprogrammingoffloppydisks(or
harddisks,whicharejustascomplexandquitedifferent).
Instead,whattheprogrammerwantsisasimple,high-level
abstractiontodealwith.Inthecaseofdisks,atypical
abstractionwouldbethatthediskcontainsacollectionof
namedfiles.Eachfilecanbeopenedforreadingorwriting,then
readorwritten,andfinallyclosed.Detailssuchaswhetheror
notrecordingshouldusemodifiedfrequencymodulationand
whatthecurrentstateofthemotorisshouldnotappearinthe
abstractionpresentedtotheuser.

[Page5]
Theprogramthathidesthetruthaboutthehardwarefromthe
programmerandpresentsanice,simpleviewofnamedfiles
thatcanbereadandwrittenis,ofcourse,theoperating
system.Justastheoperatingsystemshieldstheprogrammer
fromthediskhardwareandpresentsasimplefile-oriented

interface,italsoconcealsalotofunpleasantbusiness
concerninginterrupts,timers,memorymanagement,andother
low-levelfeatures.Ineachcase,theabstractionofferedbythe
operatingsystemissimplerandeasiertousethanthatoffered


bytheunderlyinghardware.
Inthisview,thefunctionoftheoperatingsystemistopresent
theuserwiththeequivalentofanextendedmachineor
virtualmachinethatiseasiertoprogramthantheunderlying
hardware.Howtheoperatingsystemachievesthisgoalisa
longstory,whichwewillstudyindetailthroughoutthisbook.To
summarizeitinanutshell,theoperatingsystemprovidesa
varietyofservicesthatprogramscanobtainusingspecial
instructionscalledsystemcalls.Wewillexaminesomeofthe
morecommonsystemcallslaterinthischapter.

1.1.2.TheOperatingSystemasaResource
Manager
Theconceptoftheoperatingsystemasprimarilyprovidingits
userswithaconvenientinterfaceisatop-downview.An
alternative,bottom-up,viewholdsthattheoperatingsystemis
theretomanageallthepiecesofacomplexsystem.Modern
computersconsistofprocessors,memories,timers,disks,mice,
networkinterfaces,printers,andawidevarietyofother
devices.Inthealternativeview,thejoboftheoperatingsystem
istoprovideforanorderlyandcontrolledallocationofthe
processors,memories,andI/Odevicesamongthevarious
programscompetingforthem.
Imaginewhatwouldhappenifthreeprogramsrunningonsome

computeralltriedtoprinttheiroutputsimultaneouslyonthe
sameprinter.Thefirstfewlinesofprintoutmightbefrom
program1,thenextfewfromprogram2,thensomefrom
program3,andsoforth.Theresultwouldbechaos.The
operatingsystemcanbringordertothepotentialchaosby
bufferingalltheoutputdestinedfortheprinteronthedisk.
Whenoneprogramisfinished,theoperatingsystemcanthen
copyitsoutputfromthediskfilewhereithasbeenstoredto


theprinter,whileatthesametimetheotherprogramcan
continuegeneratingmoreoutput,oblivioustothefactthatthe
outputisnotreallygoingtotheprinter(yet).
Whenacomputer(ornetwork)hasmultipleusers,theneedfor
managingandprotectingthememory,I/Odevices,andother
resourcesisevengreater,sincetheusersmightotherwise
interferewithoneanother.Inaddition,usersoftenneedto
sharenotonlyhardware,butinformation(files,databases,etc.)
aswell.Inshort,thisviewoftheoperatingsystemholdsthat
itsprimarytaskistokeeptrackofwhoisusingwhichresource,
tograntresourcerequests,toaccountforusage,andto
mediateconflictingrequestsfromdifferentprogramsandusers.

[Page6]
Resourcemanagementincludesmultiplexing(sharing)
resourcesintwoways:intimeandinspace.Whenaresourceis
timemultiplexed,differentprogramsoruserstaketurnsusing
it.Firstoneofthemgetstousetheresource,thenanother,and
soon.Forexample,withonlyoneCPUandmultipleprograms
thatwanttorunonit,theoperatingsystemfirstallocatesthe

CPUtooneprogram,thenafterithasrunlongenough,another
onegetstousetheCPU,thenanother,andtheneventuallythe
firstoneagain.Determininghowtheresourceistime
multiplexedwhogoesnextandforhowlongisthetaskofthe
operatingsystem.Anotherexampleoftimemultiplexingis
sharingtheprinter.Whenmultipleprintjobsarequeuedupfor
printingonasingleprinter,adecisionhastobemadeabout
whichoneistobeprintednext.
Theotherkindofmultiplexingisspacemultiplexing.Insteadof
thecustomerstakingturns,eachonegetspartoftheresource.
Forexample,mainmemoryisnormallydividedupamong
severalrunningprograms,soeachonecanberesidentatthe
sametime(forexample,inordertotaketurnsusingtheCPU).
Assumingthereisenoughmemorytoholdmultipleprograms,it


ismoreefficienttoholdseveralprogramsinmemoryatonce
ratherthangiveoneofthemallofit,especiallyifitonlyneeds
asmallfractionofthetotal.Ofcourse,thisraisesissuesof
fairness,protection,andsoon,anditisuptotheoperating
systemtosolvethem.Anotherresourcethatisspace
multiplexedisthe(hard)disk.Inmanysystemsasingledisk
canholdfilesfrommanyusersatthesametime.Allocatingdisk
spaceandkeepingtrackofwhoisusingwhichdiskblocksisa
typicaloperatingsystemresourcemanagementtask.





×