Linux操作系统实验.docx

上传人:夺命阿水 文档编号:991003 上传时间:2024-02-22 格式:DOCX 页数:24 大小:62.37KB
返回 下载 相关 举报
Linux操作系统实验.docx_第1页
第1页 / 共24页
Linux操作系统实验.docx_第2页
第2页 / 共24页
Linux操作系统实验.docx_第3页
第3页 / 共24页
Linux操作系统实验.docx_第4页
第4页 / 共24页
Linux操作系统实验.docx_第5页
第5页 / 共24页
点击查看更多>>
资源描述

《Linux操作系统实验.docx》由会员分享,可在线阅读,更多相关《Linux操作系统实验.docx(24页珍藏版)》请在课桌文档上搜索。

1、Project1SystemsProgrammingPractice:TheYalnixShellEducationalObjectives:Studentscometothiscoursewithvariousexperiences.Formanypeoplethisprojectwillbepracticeand/orawarmup.Forothers,itW川bealearningexercise.Regardlessofyourbackground,bytheendofthisproject,wehopethatyouwillcomfortablyandconfidentlybeabl

2、etodothefollowing: Developclear,readable,well-documentedandwell-designedprogramsintheCProgrammingLanguage. DevelopsoftwareintheUnix/Linuxusingtoolssuchasgcc,gdb,andmake. 1.ocateandinterpreting,manpagesapplicabletoapplication-levelsystemprogramming. UsethePOSIX/UnixAPItosystemfunctionstomanageprocess

3、andsessionsaswellasusesignalsandpipesforinter-processcommunication. Understandinghowsynchronizationmightbecomeproblematicinlightofconcurrency. Understandhowtocommunicateandcooperatewithaprojectpartner.ProjectOverviewInthisprojectyouareaskedtoimplementasimplecommand-interpreter,a.k,a.shell,forLinux.T

4、heshellthatyouwillimplement,knownasysh,shouldbesimilartopopularshellssuchasbash,csh1tcsh1zsh,&c,butitisnotrequiredtoimplementasmanyfeaturesasthesecommercial-gradeproducts.Althoughwedontrequireallofthe*,bellsandwhistlesthatareincorporatedintocommercial-gradeproducts,yshshouldhavemuchoftheimportantfun

5、ctionality: Allowtheusertoexecuteoneormoreprograms,fromexecutablefilesonthefile-system,asbackgroundorforegroundjobs. Providejob-control,includingajoblistandtoolsforchangingtheforeground/backgroundstatusofcurrentlyrunningjobsandjobsuspension/continuation/termination. Allowforthepipingofseveraltasksas

6、wellasinputandoutputredirection.Withrespecttotheotherprogrammingassignmentsthissemester,andmanyothersinyourexperience,thisislikelytobeasmallproject,butwewantyoutoapproachitasifitisabiggerandmorecomplexprojectsothatyouarepreparedfortheremainingprojects.Specifically,we,dlikeyoutodothefollowing: Usethe

7、makeutilitytobuildyourproject Useadebuggerinsteadofprint-ad-huntdebuggingwheneverpractical. Produceclean,well-documented,andwell-designedsolutions.SpecificationFormYoursolutionshouldbeanapplicationprograminvokedwithoutcommand-lineparametersorconfigurationfiles,&c.Ifyouwanttobefancyandsupportforareso

8、urcefilesimilartothoseusedwithcommercial-gradeshells,e.g.cshrc,you,reawelcometodothis.But,likecsh,yourshellshouldfunctioncorrectlyinabsenceofthisfile.1.ook-and-FeelThelookandfeelofyshshouldbeSimilartothatofotherUNIXshells,suchasbash,tcsh,csh,&c.Forexample,yourshellsworkloopshouldproduceaprompt,e.g.,

9、ysh,acceptinputfromtheuser,andthenproduceanotherprompt.Messagesshouldbewrittentothescreenasnecessary,andthepromptshouldbedelayedwhenuserinputshouldn,tbeaccepted,asnecessary.Needlesstosay,yourshellshouldtakeappropriateactioninresponsetotheuserSinput.InternalCommandsvs.ExternalProgramsInmostcases,theu

10、ser*sinputwillbeacommandtoexecuteprogramsstoredwithinafilesystem.We,Ilcalltheseexternalprograms.Yourshellshouldallowtheseprogramstoexecutewithstdinand/orstdoutreassignedtoafile.ItshouldallowprogramsI/Otobechainedtogetherusingpipes.Forourpurposes,acollectionofpipedprocessesorasingleprocessexecutedbyi

11、tselffromthecommandlineiscalledajob.Whenexecutingbackgroundsjobs,theshellshouldnotwaitforthejobtofinishbeforeprompting,reading,andprocessingthenextcommand.Whenabackgroundjobfinallyterminatesamessagetothateffectmustbeprinted,bytheshell,totheterminal.Thismessageshouldbeprintedassoonasthejobterminates.

12、ThesyntaxfordoingthiswillbedescribedinthesectionofthisdocumentdescribingtheshellSparser.Yourparsershouldalsosupportseveralinterna!commandsthesecommands,ifissuedbytheuser,shoulddirecttheshelltotakeaparticularactionitselfinsteadofdirectingittoexecuteotherprograms.Thedetailsofthisarediscussedinthesecti

13、ondescribinginternalcommands.Foregroundvs.BackgroundJobsYourshellshouldbecapableofexecutingbothforegroundandbackgroundjobs.Whereasyourshellshouldwaitforforegroundjobstocompletebeforecontinuing,itshouldimmediatelycontinue,prompttheuser,&c,afterplacingajobintothebackground.CommandlinesWhentheuserrespo

14、ndstoaprompt,whattheytypecomposesacommandHnestring.Yourshellshouldstoreeachcommand-linestring,untilthejobisfinishedexecuting.Thisincludesbothbackgroundandsuspendedjobs.Theshellshouldassigneachcommand-linestringanon-negativeintegeridentifier.Thedatastructureusedtostorethejobsshouldallowaccesstoeachel

15、ementusingthisidentifier.Oncetheactionsdirectedbyacommand-linestringarecompleted,yourshellshouldremoveitfromthedatastructure.Identifierscanberecycledifyouchoose.Pleasenotethatthisdatastructureshouldkeeptrackofwholecommandlinestrings,notjustthenamesoftheindividualtasksthatmaycomposethem.Youshouldnotk

16、eeptrackofcommandlinestringsthatcontaininternalcommands,since,bytheirnature,theywillcompletebeforethisinformationcouldbecomeuseful.InternalCommandsThefollowingaretheinternalcommands.Ifaninternalcommandissubmittedbytheuser,theshellshouldtakethedescribedactionsitself.exit:Killallchildprocessesandexity

17、shwithameaningfulreturncode.jobs:Printoutthecommandlinestringsforjobsthatarecurrentlyexecutinginthebackgroundandjobsthatarecurrentlysuspended,aswellastheidentifierassociatedwitheachcommandlinestring.Youmayformattheoutputofthiscommandinwaythatisconvenienttotheuser.Pleaserememberthatjobsitselfisaninte

18、rnalcommandandconsequentlyshouldnotappearintheoutput. echo$status:Printstheexitstatusofthemostrecentforegroundchildprocesstohaveexited.Return0ifnosuchchildhasexisted. fg%:Bringsthejobidentifiedbyintotheforeground.Ifthisjobwaspreviouslystopped,itshouldnowberunning.Yourshellshouldwaitforaforegoundchil

19、dtoterminatebeforereturningacommandpromptortakinganyotheraction. bg%:Executethesuspendedjobidentifiedbyinthebackground. InternalcommandscantakeadvantageofpipedI/O,executeinthebackground,&c,asappropriate.SpecialKeystrokesThroughaninteractionwiththeterminaldriver,certaincombinationsofkeystrokeswillgen

20、eratesignalstoyourshellinsteadofappearingwithinstdin.Yourshellshouldrespondappropriatelytothesesignals. Control-ZgeneratesaSIGSTOP.Thisshouldnotcauseyourshelltobesuspended.Instead,itshouldcauseyourshelltosuspendtheprocessesinthecurrentforegroundjob.Ifthereisnoforegroundjob,itshouldhavenoeffect. Cont

21、rol-CgeneratesaSIGINT.Thisshouldnotkillyourshell.Insteaditshouldcauseyourshelltokilltheprocessesinthecurrentforegroundjob.Ifthereisnoforegroundjob,itshouldhavenoeffect.ParsingUserInput-Overview,DelimitersandSpecialCharactersYourparserforuserinputshouldbecapableofacceptinginputfromtheuserasdescribedi

22、nthissection.Itshouldalsodetectimproperinputfromtheuser.Iftheuserenterssomethingimproper,yourshellshouldproduceameaningfulerrormessage.Justlikecommercial-gradeshells,yourshellshouldacceptinputfromtheuseronelineatatime.Youshouldbeginparsingtheusersinputwhenhe/shehitsenter.Emptycommandlinesshouldbetre

23、atedasno-opsandyieldanewprompt.Blank-spacecharactersshouldbetreatedasdelimiters,butyourshellshouldbeinsensitivetorepeatedblankspaces.Itshouldalsobeinsensitivetoblankspacesatthebeginningorendofthecommandline.Certaincharacters,knownasmeta-characters,havespecialmeaningswithinthecontextofuserinput.These

24、charactersinclude&,Yourshellcanassumethatthesemeta-characterscannotoccurinsidestringsrepresentingprograms,arguments,orfiles.Insteadtheyarereservedforusebytheshell.Thepurposeofmeta-charactersisdiscussedlaterinthissection.ParsingUserInput-InternalCommandsIfthecommandlinematchestheformatofaninternalcom

25、mandasdescribedearlierinthisdocument,itshouldbeacceptedasaninternalcommand.Ifnot,itshouldbeconsideredtospecifytheexecutionofexternalprograms,oranerror,asappropriate.ParsingUserInput-ExecutingASingleProgramTheexecutionofaprogramisspecifiedbyasequenceofdelimitedstrings.Thefirstoftheseisthenameoftheexe

26、cutablefilethatcontainsthedesiredprogram(moduloasearchpathasexplainedintheeecvpmanpage,seeman-s2execvp)andtheothersareargumentspassedtotheprogram.Thecommandisanerroriftheexecutablefilenamedbythefirststringdoesnotexist,orisnotanexecutable.ParingUserInput-I/ORedirectionAprogramsexecutionspecifiedasabo

27、vemaybefollowedbythemeta-characterwhichisinturnfollowedbyafilename.Inthecaseof,theoutputoftheprogramwillberedirectedtothespecifiedfilename.Iftheoutputfiledoesnotexist,itshouldbecreated.Iftheinputfiledoesnotexist,thisisanerror.ParsingUserInput-PipesandCooperatingProgramsSeveralprograminvocationscanbe

28、presentinasinglecommandline,whenseparatedbytheshellmetacharacterT.Inthiscase,theshellshouldforkallofthem,chainingtheiroutputsandinputsusingpipesappropriately.Forinstance,thecommandlineprogAargAlargA2outfileshouldforkprogAandprogB,maketheinputforprogAcomefromfileinfile,theoutputfromprogAgototheinputo

29、fprogB,andtheoutputofprogBgotothefileoutfile.ThisshouldbeaccomplishedusingapipeIPCprimative.Acommandlinewithoneormorepipesisanerrorifanyofitscomponentprograminvocationsisanerror.Acommandlinewithpipesisanerroriftheinputofanybutthefirstcommandisredirected,oriftheoutputofanybutthelastcommandisredirecte

30、d.Ajobconsistingofpipedprocessesisnotconsideredtohavecompleteduntilallofitscomponentprocesseshavecompleted.ParsingUserInput-BackgroundJobsTheusercanspecifythatajobshouldbeexecutedinthebackgroundbyendingthecommandlinewiththemeta-character&.Ifthisisthecase,allprograminvocationsrequiredbythecommandline

31、aretobecarriedoutinthebackground.ParsingUserInput-AGrammarThegrammarbelowprovidesamoreformaldescriptionofthesyntaxgoverninguserinput.Ifyouareusinglex/yacctoimplementyourparser,you*IlhavetomassagethegrammarslightlytomakeitLALR(I).Thisgrammardoesn,tincludethespecialkeystrokes,becausetheywontshowupinst

32、dinasuserinputandshouldbehandledseparately.ACommandLineislegalinputprovidedbytheuser,asadirectiontotheshell,inresponsetotheprompt.Thegrammarassumesthattheexistenceofalexicalanalyzerthatconsidersblank-spacetobeadelimiter,recognizesthemeta-charactersastokens,&c.CommandLine= NULLFgCommandLineFgCommandL

33、ine &FgCommandLine:= SimpIeCommandFirstCommand MidCommand LastCommandSimpIeCommand:= Proglnvocation InputRedirect OutputRedirectFirstCommand=Proglnvocation InputRedirectMidCommand := NULL I Proglnvocation MidCommandLastCommand= I Proglnvocation OutputRedirectProglnvocation :=ExecFiIe ArgsInputRedire

34、ct :=NULL STRINGExecFiIe :=STRINGA SuggestedPlan Of Attack1) Readthemanpagesforfork,exec,waitandexit.2) Writeafewsmallprogramstoexperimentwiththesecommands.3) Readthemanpagesfortcsetgrp()andsetpgid()4) Writesomecodetoexperimentwithprocessgroups,&c.PayattentiontoSIGTTIN&S1GTTOU.5) Designyourparser.6)

35、 Implementyourparser.7) Usingyourparser,writeasimpleshellthatcanexecutesinglecommands.8) Addsupportforrunningprogramsinthebackground,butdontworryaboutprintingthemessagewhenabackgroundjobterminates(asynchronousnotification).Addthejobscommandwhileyouaredoingthis-itmayprovehelpfulfordebugging.9) Addinp

36、utandoutputredirection10) Addcodetoprintamessagewhenabackgroundjobterminates.11) Addjobcontrolfeatures-implementthebehaviorofControl-Z(and,ifapplicable,CONTROL-C)tfgandbg.12) Addsupportforpipes.13) Finishupallofthedetails14) Test,testtest.15) CelebrateEnvironmentWhereasyoucandothisassignmentonanyUNI

37、X,itmustrunontheLinuxmachinesforyourdemo.Weencourageyoutoworkinthatenvironment,becausethelibrariesforfutureprojectsareonlyavailableintheAndrewenvironment.Althoughyoucansolvethisassignmentinyourchoiceoflanguages,itwouldprobablybemoredifficultinanythingotherthanC(orperhapsC+).Westronglyencourageyoutou

38、seC.ForfutureprojectsyoullalmostcertainlyhavetouseC.C+maywork,butweoffernoguarantees.Thereisadifferenceinthelinkingconventionbetweenthetwolanguagesthatcausesincompatibilities.Wevetriedtocorrectthis,butwemakenopromisesaboutC+.SomeUsefulInformation(Someofwhichisareview)SystemCallsYouhaveprobablyalread

39、yheardthetermSystemCall,Doyouknowwhatitmeans?Asitsnameimplies,asystemcallisa,cal*,thatis,atransferofcontrolfromoneinstructiontoadistantinstruction.Asystemcallisdifferentfromaregularprocedurecallinthatthecalleeisexecutedinaprivilegedstate,i.e,thatthecalleeiswithintheoperatingsystem.Because,forsecurit

40、yandsanity,callsintotheoperatingsystemmustbecarefullycontrolled,thereisawell-definedandlimitedsetofsystemcalls.Thisrestrictionisenforcedbythehardwarethroughtrapvectors:onlythoseOSaddressesentered,atboottime,intothetrap(interrupt)vectorarevaliddestinationsofasystemcall.Thus,asystemcallisacallthattres

41、passesaprotectionboundaryinacontrolledmanner.SincetheprocessabstractionismaintainedbytheOS,yshwillneedtomakecallsintotheOSinordertocontrolitschildprocesses.Thesecallsaresystemcalls.InUNIX,youcandistinguishsystemcallsfromuser-levellibrary(programmersAPI)callsbecausesystemcallsappearinsection2oftheman

42、ual,whereasuser-levelcallsappearinsection3ofthemanual.Themanualis,inUNIX,whatyougetwhenyouusethemancommand.Forexample,manforkwillgetyouthemanpageinsection2ofthemanualthatdescribesthefork()syscall1andman-s2execwillgetyouthemanpagethatdescribesthefamilyofexecsyscalls(asyscall,hence-s2.)ThefollowingUNI

43、Xsyscallsmayprovetobeespeciallyusefulinyoursolutiontothisproject.Thereareplentyofothers,soyoumayfind*,maandgoodreferencebooksuseful,especiallyifyouarenewtosystemprogramming. pid_tfork(void):ItcreatesaprocessthatisanaImost-exactcopyofthecallingprocess;inparticular,afterasuccessfulreturnfromfork(),bot

44、hparentandchildprocessesareexecutingthesameprogram.Thetwoprocessescanbedistinguishedbythereturnvaluefromfork(). intexecvp(constchar*file,char*constargv):Loadstheexecutablefilepath,orafilefoundthroughasearchpath,intothememoryassociatedwiththecallingprocess,andstartsexecutingtheprogramtherein.Ifsucces

45、sful,itobliterateswhateverprogramiscurrentlyrunninginthecallingprocess.Thereareseveralother,similarformsofexec. voidexit(intstatus):Exitsthecallingprogram,destroyingthecallingprocess.Itreturnsstatusastheexitvaluetotheparent,shouldtheparentbeinterested.Theparentreceivesthisexitvaluethroughthewaitsysc

46、all,below.Notethatthelinkerintroducesanexit()callattheendofeveryprogram,forinstance,attheendofacmainprocedure,eveniftheccodedoesntexplicitlyhaveone. pid_twait(int*stat_loc):Returnstheexitstatusofanexitedchild,ifany.Returnserroriftherearenochildrenrunning.Blocksthecallingprocessuntilachildexitsifther

47、earechildrenbuttheyareallcurrentlyrunning. pid_twaitpid(pid_tpid,int*stat_loc,intoptions):Similartowait()butallowsyoutowaitforaspecificprocessofgroupofprocesses,andallowsthespecificationofflagssuchaswnohang. wait3(.),wait4(.):Similartowait()butallowdifferentcombinationsofparametersandflags. inttcset

48、pgrp(intfildes,pid_tpgidjd):Setstheforegroundprocessgroupidtobetheforegroundgroupassociatedwiththecontrollingterminal.Thecontrollingterminalisusuallyassociatedwithstdin,stdout,andstderr(filedescriptorsO11,and2) intsetpgid(pid_tpid,pid_tpgid):SetstheprocessgroupIDoftheprocesswithIDpidtopgid. intdup2(intfiledes,intfiledes2):Causesthefiledescriptorfiledes2torefertothesamefileasfiledes.

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 在线阅读 > 生活休闲


备案号:宁ICP备20000045号-1

经营许可证:宁B2-20210002

宁公网安备 64010402000986号