Theoperatingsystemactsasaninterfacebetweenanapplicationandthehardware.Theuser
interactswiththehardwarefrom"theotherside".Theoperatingsystemisasetofserviceswhich
simplifiesdevelopmentofapplications.Executingaprograminvolvesthecreationofaprocessbythe
operatingsystem.Thecreatesaprocessbyassigningmemoryandotherresources,establish-ingapriorityfortheprocess(inmulti-taskingsystems),loadingprogramcodeintomemory,andexecutingtheprogram.Theprogram
theninteractswiththeuserand/orotherdevicesandperformsitsintendedfunction.
操作系统在应用程序和硬件之间扮演了一个接口的角色,用户在(接口的)另外一端和硬件进行交互。操作系统是一个简化了应用程序开发过程的服务的一个集合。执行一个程序牵涉到操作系统创建进程。内核通过分配相应的内存空间和其他资源,在多任务系统中还要确定进程的优先级别,将程序代码载入内存然后执行程序(的一系列工作)来创建一个进程。然后进程才和用户或者其他设备进行交互来发挥它应有的功能。
Interruptsarecentraltooperatingsystems,astheyprovideanefficientwayfortheoperating
systemtointeractwithandreacttoitsenvironment.Thealternative—havingtheoperatingsystem"watch"thevarioussourcesofinputforevents(polling)thatrequire
action—canbefoundinoldersystemswithverysmall(50or60bytes)butfairlyunusualinmodern
systemswithfairlylargestacks.-basedprogrammingisdirectlysupportedbymostmodernCPUs.Interruptsprovideacomputerwith
awayofautomaticallysavinglocalregistercontexts,andrunningspecificcodeinresponsetoevents
.Evenverybasiccomputerssupporthardwareinterrupts,andallowtheprogrammertospecifycode
whichmayberunwhenthateventtakesplace.
中断是操作系统的核心,因为他们为操作系统提供了和他所处的环境之间的交互提供了一种有效的方式。我们可选择的让操作系统监视多样化的输入事件资源,在老的操作系统中我们可以发现非常小的栈(一般50-60字节)但是这些东西在具有相当大的堆栈空间中又变得相当少见了。基于中断的编程技术可以被大多数现代的CPU直接支持。中断机制为计算机提供了一种自动保存本地寄存器上下文、然后执行特殊代码相应输入事件的方式。即便是在最普通的计算机里也支持硬件中断,允许程序员编写在相应事件发生时可以执行的特殊代码。
Whenaninterruptisreceived,thecomputer'shardwareautomaticallysuspendswhateverprogramis
currentlyrunning,savesitsstatus,andrunscomputercodepreviouslyassociatedwiththeinterrupt;
thisisanalogoustoplacingabookmarkinabookinresponsetoaphonecall.Inmodernoperating
systems,interruptsarehandledbytheoperatingsystem's.Interruptsmaycomefromeither
thecomputer'shardwareorfromtherunningprogram.
Whenahardwaredevicetriggersaninterrupt,theoperatingsystem'skerneldecideshowtodealwith
thisevent,generallybyrunningsomeprocessingcode.Theamountofcodebeingrundependson
thepriorityoftheinterrupt(forexample:apersonusuallyrespondstoasmokedetectoralarm
beforeansweringthephone).Theprocessingofhardwareinterruptsisataskthatisusuallydelegated
anotherprogram,orboth.Devicedriversmaythenrelayinformationtoarunningprogramby
variousmeans.
Aprogrammayalsotriggeraninterrupttotheoperatingsystem.Ifaprogramwishestoaccess
hardwareforexample,itmayinterrupttheoperatingsystem'skernel,whichcausescontroltobe
passedbacktothekernel.Thekernelwillthenprocesstherequest.Ifaprogramwishesadditional
resources(orwishestoshedresources)suchasmemory,itwilltriggeraninterrupttogetthekernel's
attention.
一个程序可能也能触发一个对操作系统的中断请求。例如,如果一个程序需要访问硬件,它可能会中断操作系统的内核运行,而这将导致控制权被转交给内核。内核然后来处理这个中断请求。如果一个程序希望额外的资源(或者希望计划中的资源)例如内存,它将会触发一个中断来引起内核的注意。
Protectedmodeisusedheremoregenerallyinoperatingsystemtheorytorefertoallmodeswhich
limitthecapabilitiesofprogramsrunninginthatmode,providingthingslikevirtualmemoryaddressing
andlimitingaccesstohardwareinamannerdeterminedbyaprogramrunninginsupervisormode.
Similarmodeshaveexistedinsupercomputers,minicomputers,andmainframesastheyare
essentialtofullysupportingUNIX-likemulti-useroperatingsystems.
一般来说,保护模式是在操作系统中使用的更为普遍的模式,为了指出所有的模式当程序在此模式下运行时的缺陷和能力,保护模式提供一些像虚拟内存地址、限制一个正在运行的进程访问内存。在超级计算机、微型机、工作站中都有类似的操作系统模式,这个模式对于支持多用户的系统像Unix是不可缺少的。
Whenacomputerfirststartsup,itisautomaticallyrunningin.Thefirstfew
programstorunonthecomputer,beingthe,andtheoperatingsystemhave
unlimitedaccesstohardware-andthisisrequiredbecause,bydefinition,initializingaprotectedenvironmentcanonlybedone
outsideofone.However,whentheoperatingsystempassescontroltoanotherprogram,itcanplace
theCPUinto.
当一个计算机启动时,它将自动在保护模式下运行。最开始的一些程序在计算机上运行,他们是BIOS,启动项加载程序。而且这时操作系统并没有限制访问硬件,这是有必要的,因为初始化一个受保护的环境只能在这个环境之外进行。然而,当操作系统把控制权交给一个程序时,它将把CPU调到保护模式下。
In,programsmayhaveaccesstoamorelimitedsetoftheCPU'sinstructions.A
userprogrammayleaveonlybytriggeringaninterrupt,causingcontroltobepassed
backtothe.Inthiswaytheoperatingsystemcanmaintainexclusivecontroloverthingslikea
ccesstohardwareandmemory.
在保护模式下,程序可能会获得一个受限制的CPU指令集。一个用户程序要离开保护模式只有通过触发中断的方式,这个中断处理的结果就是控制权被返回给操作系统内核。用这种方式操作系统可以维持在类似于硬件和内存之类的资源上的互斥控制。
Theterm"protectedmoderesource"generallyreferstooneormoreCPUregisters,whichcontain
informationthattherunningprogramisn'tallowedtoalter.Attemptstoaltertheseresources
generallycausesaswitchtosupervisormode,wheretheoperatingsystemcandealwiththeillegal
operationtheprogramwasattempting(forexample,bykillingtheprogram).
术语“保护模式下的资源”通常是指一个或多个寄存器,这些寄存器内含有正在执行的程序不允许改变的信息。试图改变这些信息将会导致一个向保护模式的转换,这里操作系统可以处理程序试图进行的非法操作(例如:终止进程)。
Amongotherthings,amultiprogrammingoperatingsystemkernelmustberesponsibleformanaging
allsystemmemorywhichiscurrentlyinusebyprograms.Thisensuresthataprogramdoesnot
interferewithmemoryalreadyusedbyanotherprogram.Sinceprogramstimeshare,eachprogram
musthaveindependentaccesstomemory.
除此之外,一个多道程序设计操作系统内核必须负责管理所有的当前被程序占用的内存。这确保了一个进程不会妨碍被其他程序占用的内存。因为程序是分时共享的,每一个程序都将独占内存。
Memoryprotectionenablesthekerneltolimitaprocess'accesstothecomputer'smemory.Various
methodsofmemoryprotectionexist,includingmemorysegmentationandpaging.Allmethodsrequire
somelevelofhardwaresupport(suchasthe80286MMU)whichdoesn'texistinallcomputers.
内存保护允许内核限制一个进程访问内存。多样的内存保护方式存在,包括内存分段分页机制。这些所有的方法都需要硬件支持(像80286微处理器单元),并不是在所有的计算机中都能用。
Inbothsegmentationandpaging,certainprotectedmoderegistersspecifytotheCPUwhatmemory
addressitshouldallowarunningprogramtoaccess.Attemptstoaccessotheraddresseswilltrigger
aninterruptwhichwillcausetheCPUtore-entersupervisormode,placingthekernelincharge.Thisiscalledasegmentationviolationor
Seg-Vforshort,andsinceitisbothdifficulttoassignameaningfulresulttosuchanoperation,and
becauseitisusuallyasignofamisbehavingprogram,thekernelwillgenerallyresorttoterminating
theoffendingprogram,andwillreporttheerror.
在分段和分页两种机制中,某种保护模式下CPU指定寄存器所存储的一段地址是允许程序访问的。试图访问其它地址将会触发一个中断这将导致CPU重新进入保护模式,恢复内核的控制权。这被称作为段错误,而由于为这样的操作设定一个有意义的结果非常困难,当然这通常作为一个错误程序的标志,内核将会终结这个错误的进程,然后报告错误。
InmostGNU/Linuxsystems,partoftheharddiskisreservedforvirtualmemorywhentheOperating
systemisbeinginstalledonthesystem.Thispartisknownasswapspace.Windowssystemsuse
aswapfileinsteadofapartition.
在大多数GNU/Linux系统中,部分硬盘空间是在安装操作系统时为虚拟内存保留的,这部分被称作为交换分区。Windows系统使用了一个交换文件来代替这部分分区。
虚拟内存
Theuseofvirtualmemoryaddressing(suchaspagingorsegmentation)meansthatthekernelcan
choosewhatmemoryeachprogrammayuseatanygiventime,allowingtheoperatingsystemto
usethesamememorylocationsformultipletasks.
Ifaprogramtriestoaccessmemorythatisn'tinitscurrentrangeofaccessiblememory,but
nonethelesshasbeenallocatedtoit,thekernelwillbeinterruptedinthesamewayasitwouldifthe
programweretoexceeditsallocatedmemory.(Seesectiononmemorymanagement.)Under
UNIXthiskindofinterruptisreferredtoasapagefault.
如果一个进程想要访问当前不在可访问内存表里的空间,但现在没有内存可以分配给它时,内核将会以和该进程需要超过的所需要的内存空间时所采取的同样的方式启动中断机制。(看下内存管理这一章节)在UNIX系统下,这种中断将会被认为是一个页错误。
Whenthekerneldetectsapagefaultitwillgenerallyadjustthevirtualmemoryrangeoftheprogram
whichtriggeredit,grantingitaccesstothememoryrequested.Thisgivesthekerneldiscretionary
poweroverwhereaparticularapplication'smemoryisstored,orevenwhetherornotithasactually
beenallocatedyet.
当内核检测到一个页错误时它将自动适应所触发他的程序的虚拟内存范围,允许他访问内存需要。这在一个特殊的应用存储空间给了内核自由的权利,或者说它实际上到现在还没被分配除去。
Inmodernoperatingsystems,memorywhichisaccessedlessfrequentlycanbetemporarilystored
ondiskorothermediatomakethatspaceavailableforusebyotherprograms.Thisiscalled
,asanareaofmemorycanbeusedbymultipleprograms,andwhatthatmemoryarea
containscanbeswappedorexchangedondemand.
Multitaskingreferstotherunningofmultipleindependentcomputerprogramsonthesamecomputer;
givingtheappearancethatitisperformingthetasksatthesametime.Sincemostcomputerscan
doatmostoneortwothingsatonetime,thisisgenerallydoneviatime-sharing,whichmeansthateachprogramusesashareofthecomputer'stimetoexecute.
Anoperatingsystemkernelcontainsapieceofsoftwarecalledaschedulerwhichdetermineshow
muchtimeeachprogramwillspendexecuting,andinwhichorderexecutioncontrolshouldbe
passedtoprograms.Controlispassedtoaprocessbythekernel,whichallowstheprogramaccess
totheCPUandmemory.Later,controlisreturnedtothekernelthroughsomemechanism,sothat
anotherprogrammaybeallowedtousetheCPU.Thisso-calledpassingofcontrolbetweenthekernelandapplicationsiscalledacontextswitch.
Anearlymodelwhichgovernedtheallocationoftimetoprogramswascalledcooperativemultitasking.
Inthismodel,whencontrolispassedtoaprogrambythekernel,itmayexecuteforaslongasit
wantsbeforeexplicitlyreturningcontroltothekernel.Thismeansthatamaliciousormalfunctioning
programmaynotonlypreventanyotherprogramsfromusingtheCPU,butitcanhangtheentire
systemifitentersaninfiniteloop.
Thephilosophygoverningpreemptivemultitaskingisthatofensuringthatallprogramsaregiven
regulartimeontheCPU.Thisimpliesthatallprogramsmustbelimitedinhowmuchtimetheyare
allowedtospendontheCPUwithoutbeinginterrupted.Toaccomplishthis,modernoperatingsystem
kernelsmakeuseofatimedinterrupt.Aprotectedmodetimerissetbythekernelwhichtriggersa
returntosupervisormodeafterthespecifiedtimehaselapsed.
内核的可抢占式
Inrecentyears,concernshavearisenbecauseoflonglatenciesassociatedwithsomekernelrun-times,sometimesontheorderof100msormoreinsystemswithmonolithickernels.Theselatencies
oftenproducenoticeableslownessindesktopsystems,andcanpreventoperatingsystemsfrom
performingtime-sensitiveoperationssuchasaudiorecordingandsomecommunications.
Modernoperatingsystemsextendtheconceptsofapplicationpreemptiontodevicedriversandkernel
code,sothattheoperatingsystemhaspreemptivecontroloverinternalrun-timesaswell.UnderWindowsVista,theintroductionoftheWindowsDisplayDriverModel(WDDM)
accomplishesthisfordisplaydrivers,andinGNU/Linux,thepreemptablekernelmodelintroducedin
version2.6allowsalldevicedriversandsomeotherpartsofkernelcodetotakeadvantageof
preemptivemulti-tasking.
UnderWindowsversionspriortoWindowsVistaandLinuxpriortoversion2.6alldriverexecutionwas
co-operative,meaningthatifadriverenteredaninfiniteloopitwouldfreezethesystem.
在Windows中的Vista和Linux中的2.6内核之前,所有的驱动执行是在一起的,这意味着如果一个驱动程序进入死循环整个系统就将被冰冻。
Accesstodatastoredondisksisacentralfeatureofalloperatingsystems.Computersstoredataon
using,whicharestructuredinspecificwaysinordertoallowforfasteraccess,higher
reliability,andtomakebetteruseoutofthedrive'savailablespace.Thespecificwayinwhichfiles
arestoredonadiskiscalledafilesystem,andenablesfilestohavenamesandattributes.Italso
allowsthemtobestoredinahierarchyofdirectoriesorfoldersarrangedinadirectorytree.
访问存储在硬盘上的数据是所有操作系统的一个主要功能。计算机以文件的形式把数据保存在硬盘上,为了高速存取,高可靠性的目的,也为了充分利用硬盘上的可用空间,它们被以特殊方式有结构的组织在一起。这种文件被存储在硬盘上的特殊方式被称作是文件系统,它允许文件具有名字和属性,也允许它们被以目录树的形式安排存储在一个分层的目录文件里。
Whilemanysimpleroperatingsystemssupportalimitedrangeofoptionsforaccessingstorage
systems,operatingsystemslikeandsupportatechnologyknownasavirtualfile
systemorVFS.AnoperatingsystemlikeUNIXsupportsawidearrayofstoragedevices,regardless
oftheirdesignorfilesystemstobeaccessedthroughacommonapplicationprogramminginterface
(API).Thismakesitunnecessaryforprogramstohaveanyknowledgeaboutthedevicetheyare
accessing.AVFSallowstheoperatingsystemtoprovideprogramswithaccesstoanunlimitednumber
ofdeviceswithaninfinitevarietyoffilesystemsinstalledonthemthroughtheuseofspecificdevice
driversandfilesystemdrivers.
当许多较简单的操作系统支持有限选择性的访问存储系统时,像UNIX和GNU/LINUX已经开始支持被叫做虚拟文件系统的新技术了。像UNIX一样的操作系统开始支持通过一个公共的应用程序接口访问一个存储设备阵列,不论这些存储设备的是怎样被设计、采用何种文件系统。这让下面一个观点变得不再是不可或缺的了,它就是程序必须了解所有它们正在访问的设备的工作方式。一个VFS可以让操作系统通过安装在它们上各种驱动程序和文件系统驱动的支持程序访问各种各样的文件系统。
driverunderstandsthespecificlanguageofthedriveandisabletotranslatethatlanguageintoa
standardlanguageusedbytheoperatingsystemtoaccessalldiskdrives.OnUNIX,thisisthe
languageofblockdevices.
一个被连接的存储设备例如硬盘,是通过设备驱动被访问的。这个设备驱动懂得和这个设备交流的“语言”,它能够将将这种语言翻译成操作系统用于访问所有设备的通用“语言”。在UNIX下,就是设备块。
Whenthekernelhasanappropriatedevicedriverinplace,itcanthenaccessthecontentsofthedisk
driveinrawformat,whichmaycontainoneormorefilesystems.Afilesystemdriverisusedto
translatethecommandsusedtoaccesseachspecificfilesystemintoastandardsetofcommands
thattheoperatingsystemcanusetotalktoallfilesystems.Programscanthendealwiththesefile
systemsonthebasisoffilenames,anddirectories/folders,containedwithinahierarchicalstructure.
Theycancreate,delete,open,andclosefiles,aswellasgathervariousinformationaboutthem,
includingaccesspermissions,size,freespace,andcreationandmodificationdates.
Variousdifferencesbetweenfilesystemsmakesupportingallfilesystemsdifficult.Allowedcharacters
infilenames,casesensitivity,andthepresenceofvariouskindsoffileattributesmakesthe
implementationofasingleinterfaceforeveryfilesystemadauntingtask.Operatingsystems
tendtorecommendusing(andsosupportnatively)filesystemsspecificallydesignedforthem;
forexample,NTFSinWindowsandext3andReiserFSinGNU/Linux.However,inpractice,third
partydrivesareusuallyavailabletogivesupportforthemostwidelyusedfilesystemsinmost
general-purposeoperatingsystems(forexample,NTFSisavailableinGNU/Linuxthrough
NTFS-3g,andext2/3andReiserFSareavailableinWindowsthroughFS-driverandrfstool).
当内核在合适的地方有一个合适的设备驱动时,它才可以访问没有格式化的硬盘里的内容,这时的硬盘可能会有一个或者多个文件系统。一个文件系统驱动程序一般是将访问某种特定文件系统的命令翻译成操作系统可以用来和各种各样的文件系统交换信息的标准命令集合。程序然后才可以在基于文件名程、包含层式目录的属性来处理这些文件系统。它们可以创建、打开、删除和关闭文件,也可以获取关于这些文件的而各种信息,包括访问权限,大小,可用空间,创建和修改日期。不同文件系统之间各种各样的差异导致支持各种文件系统是很困难的。文件名中允许包含的字符、环境敏感性,以及多种多样的文件属性的表述让对各种操作系统只有一个单一接口实现起来真是一项很繁重的工作。操作系统倾向于使用一些专门为它们设计的文件系统,例如Windows中的NTFS,GNU/LINUX中的EXT3格式文件系统。然而,在实践中,第三方驱动通常用于支持许多在大多数操作系统广泛使用的文件系统(例如,GNU/Linux系统通过NTFS-3g可以使用NTFS文件系统,Windows通过FS-driver和rfs-tool可以访问ext2/3文件系统)。