欢迎来到课桌文档! | 帮助中心 课桌文档-建筑工程资料库
课桌文档
全部分类
  • 党建之窗>
  • 感悟体会>
  • 百家争鸣>
  • 教育整顿>
  • 文笔提升>
  • 热门分类>
  • 计划总结>
  • 致辞演讲>
  • 在线阅读>
  • ImageVerifierCode 换一换
    首页 课桌文档 > 资源分类 > DOCX文档下载  

    Linux操作系统实验.docx

    • 资源ID:991003       资源大小:62.37KB        全文页数:24页
    • 资源格式: DOCX        下载积分:5金币
    快捷下载 游客一键下载
    会员登录下载
    三方登录下载: 微信开放平台登录 QQ登录  
    下载资源需要5金币
    邮箱/手机:
    温馨提示:
    用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)
    支付方式: 支付宝    微信支付   
    验证码:   换一换

    加入VIP免费专享
     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    Linux操作系统实验.docx

    Project1SystemsProgrammingPractice:TheYalnixShellEducationalObjectives:Studentscometothiscoursewithvariousexperiences.Formanypeoplethisprojectwillbepracticeand/orawarmup.Forothers,itW川bealearningexercise.Regardlessofyourbackground,bytheendofthisproject,wehopethatyouwillcomfortablyandconfidentlybeabletodothefollowing: Developclear,readable,well-documentedandwell-designedprogramsintheCProgrammingLanguage. DevelopsoftwareintheUnix/Linuxusingtoolssuchasgcc,gdb,andmake. 1.ocateandinterpreting,manpages"applicabletoapplication-levelsystemprogramming. UsethePOSIX/UnixAPItosystemfunctionstomanageprocessandsessionsaswellasusesignalsandpipesforinter-processcommunication. Understandinghowsynchronizationmightbecomeproblematicinlightofconcurrency. Understandhowtocommunicateandcooperatewithaprojectpartner.ProjectOverviewInthisprojectyouareaskedtoimplementasimplecommand-interpreter,a.k,a."shell,"forLinux.Theshellthatyouwillimplement,knownasysh,shouldbesimilartopopularshellssuchasbash,csh1tcsh1zsh,&c,butitisnotrequiredtoimplementasmanyfeaturesasthesecommercial-gradeproducts.Althoughwedon'trequireallofthe*,bellsandwhistles"thatareincorporatedintocommercial-gradeproducts,yshshouldhavemuchoftheimportantfunctionality: Allowtheusertoexecuteoneormoreprograms,fromexecutablefilesonthefile-system,asbackgroundorforegroundjobs. Providejob-control,includingajoblistandtoolsforchangingtheforeground/backgroundstatusofcurrentlyrunningjobsandjobsuspension/continuation/termination. Allowforthepipingofseveraltasksaswellasinputandoutputredirection.Withrespecttotheotherprogrammingassignmentsthissemester,andmanyothersinyourexperience,thisislikelytobeasmallproject,butwewantyoutoapproachitasifitisabiggerandmorecomplexprojectsothatyouarepreparedfortheremainingprojects.Specifically,we,dlikeyoutodothefollowing: Usethemakeutilitytobuildyourproject Useadebuggerinsteadofprint-ad-huntdebuggingwheneverpractical. Produceclean,well-documented,andwell-designedsolutions.SpecificationFormYoursolutionshouldbeanapplicationprograminvokedwithoutcommand-lineparametersorconfigurationfiles,&c.Ifyouwanttobefancyandsupportforaresourcefilesimilartothoseusedwithcommercial-gradeshells,e.g.cshrc,you,reawelcometodothis.But,likecsh,yourshellshouldfunctioncorrectlyinabsenceofthisfile.1.ook-and-FeelThelookandfeelofyshshouldbeSimilartothatofotherUNIXshells,suchasbash,tcsh,csh,&c.Forexample,yourshell'sworkloopshouldproduceaprompt,e.g.,ysh>,acceptinputfromtheuser,andthenproduceanotherprompt.Messagesshouldbewrittentothescreenasnecessary,andthepromptshouldbedelayedwhenuserinputshouldn,tbeaccepted,asnecessary.Needlesstosay,yourshellshouldtakeappropriateactioninresponsetotheuser'Sinput.InternalCommandsvs.ExternalProgramsInmostcases,theuser*sinputwillbeacommandtoexecuteprogramsstoredwithinafilesystem.We,Ilcalltheseexternalprograms.Yourshellshouldallowtheseprogramstoexecutewithstdinand/orstdoutreassignedtoafile.ItshouldallowprogramsI/Otobechainedtogetherusingpipes.Forourpurposes,acollectionofpipedprocessesorasingleprocessexecutedbyitselffromthecommandlineiscalledajob.Whenexecutingbackgroundsjobs,theshellshouldnotwaitforthejobtofinishbeforeprompting,reading,andprocessingthenextcommand.Whenabackgroundjobfinallyterminatesamessagetothateffectmustbeprinted,bytheshell,totheterminal.Thismessageshouldbeprintedassoonasthejobterminates.Thesyntaxfordoingthiswillbedescribedinthesectionofthisdocumentdescribingtheshell'Sparser.Yourparsershouldalsosupportseveralinterna!commandsthesecommands,ifissuedbytheuser,shoulddirecttheshelltotakeaparticularactionitselfinsteadofdirectingittoexecuteotherprograms.Thedetailsofthisarediscussedinthesectiondescribinginternalcommands.Foregroundvs.BackgroundJobsYourshellshouldbecapableofexecutingbothforegroundandbackgroundjobs.Whereasyourshellshouldwaitforforegroundjobstocompletebeforecontinuing,itshouldimmediatelycontinue,prompttheuser,&c,afterplacingajobintothebackground.CommandlinesWhentheuserrespondstoaprompt,whattheytypecomposesacommandHnestring.Yourshellshouldstoreeachcommand-linestring,untilthejobisfinishedexecuting.Thisincludesbothbackgroundandsuspendedjobs.Theshellshouldassigneachcommand-linestringanon-negativeintegeridentifier.Thedatastructureusedtostorethejobsshouldallowaccesstoeachelementusingthisidentifier.Oncetheactionsdirectedbyacommand-linestringarecompleted,yourshellshouldremoveitfromthedatastructure.Identifierscanberecycledifyouchoose.Pleasenotethatthisdatastructureshouldkeeptrackofwholecommandlinestrings,notjustthenamesoftheindividualtasksthatmaycomposethem.Youshouldnotkeeptrackofcommandlinestringsthatcontaininternalcommands,since,bytheirnature,theywillcompletebeforethisinformationcouldbecomeuseful.InternalCommandsThefollowingaretheinternalcommands.Ifaninternalcommandissubmittedbytheuser,theshellshouldtakethedescribedactionsitself.exit:Killallchildprocessesandexityshwithameaningfulreturncode.jobs:Printoutthecommandlinestringsforjobsthatarecurrentlyexecutinginthebackgroundandjobsthatarecurrentlysuspended,aswellastheidentifierassociatedwitheachcommandlinestring.Youmayformattheoutputofthiscommandinwaythatisconvenienttotheuser.Pleaserememberthatjobsitselfisaninternalcommandandconsequentlyshouldnotappearintheoutput. echo$status:Printstheexitstatusofthemostrecentforegroundchildprocesstohaveexited.Return0ifnosuchchildhasexisted. fg%<int>:Bringsthejobidentifiedby<it>intotheforeground.Ifthisjobwaspreviouslystopped,itshouldnowberunning.Yourshellshouldwaitforaforegoundchildtoterminatebeforereturningacommandpromptortakinganyotheraction. bg%<int>:Executethesuspendedjobidentifiedby<int>inthebackground. InternalcommandscantakeadvantageofpipedI/O,executeinthebackground,&c,asappropriate.SpecialKeystrokesThroughaninteractionwiththeterminaldriver,certaincombinationsofkeystrokeswillgeneratesignalstoyourshellinsteadofappearingwithinstdin.Yourshellshouldrespondappropriatelytothesesignals. Control-ZgeneratesaSIGSTOP.Thisshouldnotcauseyourshelltobesuspended.Instead,itshouldcauseyourshelltosuspendtheprocessesinthecurrentforegroundjob.Ifthereisnoforegroundjob,itshouldhavenoeffect. Control-CgeneratesaSIGINT.Thisshouldnotkillyourshell.Insteaditshouldcauseyourshelltokilltheprocessesinthecurrentforegroundjob.Ifthereisnoforegroundjob,itshouldhavenoeffect.ParsingUserInput-Overview,DelimitersandSpecialCharactersYourparserforuserinputshouldbecapableofacceptinginputfromtheuserasdescribedinthissection.Itshouldalsodetectimproperinputfromtheuser.Iftheuserenterssomethingimproper,yourshellshouldproduceameaningfulerrormessage.Justlikecommercial-gradeshells,yourshellshouldacceptinputfromtheuseronelineatatime.Youshouldbeginparsingtheusersinputwhenhe/shehitsenter.Emptycommandlinesshouldbetreatedasno-opsandyieldanewprompt.Blank-spacecharactersshouldbetreatedasdelimiters,butyourshellshouldbeinsensitivetorepeatedblankspaces.Itshouldalsobeinsensitivetoblankspacesatthebeginningorendofthecommandline.Certaincharacters,knownasmeta-characters,havespecialmeaningswithinthecontextofuserinput.Thesecharactersinclude&,<,and>,Yourshellcanassumethatthesemeta-characterscannotoccurinsidestringsrepresentingprograms,arguments,orfiles.Insteadtheyarereservedforusebytheshell.Thepurposeofmeta-charactersisdiscussedlaterinthissection.ParsingUserInput-InternalCommandsIfthecommandlinematchestheformatofaninternalcommandasdescribedearlierinthisdocument,itshouldbeacceptedasaninternalcommand.Ifnot,itshouldbeconsideredtospecifytheexecutionofexternalprograms,oranerror,asappropriate.ParsingUserInput-ExecutingASingleProgramTheexecutionofaprogramisspecifiedbyasequenceofdelimitedstrings.Thefirstoftheseisthenameoftheexecutablefilethatcontainsthedesiredprogram(moduloasearchpathasexplainedintheeecvpmanpage,seeman-s2execvp)andtheothersareargumentspassedtotheprogram.Thecommandisanerroriftheexecutablefilenamedbythefirststringdoesnotexist,orisnotanexecutable.ParingUserInput-I/ORedirectionAprogram'sexecutionspecifiedasabovemaybefollowedbythemeta-character<or>whichisinturnfollowedbyafilename.Inthecaseof<1theinputoftheprogramwillberedirectedfromthespecifiedfilename.Inthecaseof>,theoutputoftheprogramwillberedirectedtothespecifiedfilename.Iftheoutputfiledoesnotexist,itshouldbecreated.Iftheinputfiledoesnotexist,thisisanerror.ParsingUserInput-PipesandCooperatingProgramsSeveralprograminvocationscanbepresentinasinglecommandline,whenseparatedbytheshellmetacharacter'T'.Inthiscase,theshellshouldforkallofthem,chainingtheiroutputsandinputsusingpipesappropriately.Forinstance,thecommandlineprogAargAlargA2<infileprogBargBl>outfileshouldforkprogAandprogB,maketheinputforprogAcomefromfileinfile,theoutputfromprogAgototheinputofprogB,andtheoutputofprogBgotothefileoutfile.ThisshouldbeaccomplishedusingapipeIPCprimative.Acommandlinewithoneormore''pipes"isanerrorifanyofitscomponentprograminvocationsisanerror.Acommandlinewith''pipes"isanerroriftheinputofanybutthefirstcommandisredirected,oriftheoutputofanybutthelastcommandisredirected.Ajobconsistingofpipedprocessesisnotconsideredtohavecompleteduntilallofitscomponentprocesseshavecompleted.ParsingUserInput-BackgroundJobsTheusercanspecifythatajobshouldbeexecutedinthebackgroundbyendingthecommandlinewiththemeta-character&.Ifthisisthecase,allprograminvocationsrequiredbythecommandlinearetobecarriedoutinthebackground.ParsingUserInput-AGrammarThegrammarbelowprovidesamoreformaldescriptionofthesyntaxgoverninguserinput.Ifyouareusinglex/yacctoimplementyourparser,you*IlhavetomassagethegrammarslightlytomakeitLALR(I).Thisgrammardoesn,tincludethespecialkeystrokes,becausetheywon'tshowupinstdinasuserinputandshouldbehandledseparately.ACommandLineislegalinputprovidedbytheuser,asadirectiontotheshell,inresponsetotheprompt.Thegrammarassumesthattheexistenceofalexicalanalyzerthatconsidersblank-spacetobeadelimiter,recognizesthemeta-charactersastokens,&c.CommandLine= NULLFgCommandLineFgCommandLine &FgCommandLine:= SimpIeCommandFirstCommand MidCommand LastCommandSimpIeCommand:= Proglnvocation InputRedirect OutputRedirectFirstCommand=Proglnvocation InputRedirectMidCommand := NULL I Proglnvocation MidCommandLastCommand= I Proglnvocation OutputRedirectProglnvocation :=ExecFiIe ArgsInputRedirect :=NULL< STRINGOutputRedirect :=NULL> STRINGExecFiIe :=STRINGA SuggestedPlan Of Attack1) Readthemanpagesforfork,exec,waitandexit.2) Writeafewsmallprogramstoexperimentwiththesecommands.3) Readthemanpagesfortcsetgrp()andsetpgid()4) Writesomecodetoexperimentwithprocessgroups,&c.PayattentiontoSIGTTIN&S1GTTOU.5) Designyourparser.6) Implementyourparser.7) Usingyourparser,writeasimpleshellthatcanexecutesinglecommands.8) Addsupportforrunningprogramsinthebackground,butdon'tworryaboutprintingthemessagewhenabackgroundjobterminates(asynchronousnotification).Addthejobscommandwhileyouaredoingthis-itmayprovehelpfulfordebugging.9) Addinputandoutputredirection10) Addcodetoprintamessagewhenabackgroundjobterminates.11) Addjobcontrolfeatures-implementthebehaviorofControl-Z(and,ifapplicable,CONTROL-C)tfgandbg.12) Addsupportforpipes.13) Finishupallofthedetails14) Test,testtest.15) CelebrateEnvironmentWhereasyoucandothisassignmentonanyUNIX,itmustrunontheLinuxmachinesforyourdemo.Weencourageyoutoworkinthatenvironment,becausethelibrariesforfutureprojectsareonlyavailableintheAndrewenvironment.Althoughyoucansolvethisassignmentinyourchoiceoflanguages,itwouldprobablybemoredifficultinanythingotherthanC(orperhapsC+).WestronglyencourageyoutouseC.Forfutureprojectsyou'llalmostcertainlyhavetouseC.C+maywork,butweoffernoguarantees.Thereisadifferenceinthelinkingconventionbetweenthetwolanguagesthatcausesincompatibilities.We'vetriedtocorrectthis,butwemakenopromisesaboutC+.SomeUsefulInformation(Someofwhichisareview)SystemCallsYouhaveprobablyalreadyheardtheterm"SystemCall,"Doyouknowwhatitmeans?Asitsnameimplies,asystemcallisa',cal*,thatis,atransferofcontrolfromoneinstructiontoadistantinstruction.Asystemcallisdifferentfromaregularprocedurecallinthatthecalleeisexecutedinaprivilegedstate,i.e,thatthecalleeiswithintheoperatingsystem.Because,forsecurityandsanity,callsintotheoperatingsystemmustbecarefullycontrolled,thereisawell-definedandlimitedsetofsystemcalls.Thisrestrictionisenforcedbythehardwarethroughtrapvectors:onlythoseOSaddressesentered,atboottime,intothetrap(interrupt)vectorarevaliddestinationsofasystemcall.Thus,asystemcallisacallthattrespassesaprotectionboundaryinacontrolledmanner.SincetheprocessabstractionismaintainedbytheOS,yshwillneedtomakecallsintotheOSinordertocontrolitschildprocesses.Thesecallsaresystemcalls.InUNIX,youcandistinguishsystemcallsfromuser-levellibrary(programmer'sAPI)callsbecausesystemcallsappearinsection2ofthe''manual",whereasuser-levelcallsappearinsection3ofthe''manual".The''manual"is,inUNIX,whatyougetwhenyouusethe''man"command.Forexample,manforkwillgetyouthe''manpage"insection2ofthemanualthatdescribesthefork()syscall1andman-s2execwillgetyouthe''manpage"thatdescribesthefamilyof''exec"syscalls(asyscall,hence-s2.)ThefollowingUNIXsyscallsmayprovetobeespeciallyusefulinyoursolutiontothisproject.Thereareplentyofothers,soyoumayfind*,ma"andgoodreferencebooksuseful,especiallyifyouarenewtosystemprogramming. pid_tfork(void):ItcreatesaprocessthatisanaImost-exactcopyofthecallingprocess;inparticular,afterasuccessfulreturnfromfork(),bothparentandchildprocessesareexecutingthesameprogram.Thetwoprocessescanbedistinguishedbythereturnvaluefromfork(). intexecvp(constchar*file,char*constargv):Loadstheexecutablefilepath,orafilefoundthroughasearchpath,intothememoryassociatedwiththecallingprocess,andstartsexecutingtheprogramtherein.Ifsuccessful,itobliterateswhateverprogramiscurrentlyrunninginthecallingprocess.Thereareseveralother,similarformsofexec. voidexit(intstatus):Exitsthecallingprogram,destroyingthecallingprocess.Itreturnsstatusastheexitvaluetotheparent,shouldtheparentbeinterested.Theparentreceivesthisexitvaluethroughthewaitsyscall,below.Notethatthelinkerintroducesanexit()callattheendofeveryprogram,forinstance,attheendofacmainprocedure,eveniftheccodedoesn'texplicitlyhaveone. pid_twait(int*stat_loc):Returnstheexitstatusofanexitedchild,ifany.Returnserroriftherearenochildrenrunning.Blocksthecallingprocessuntilachildexitsiftherearechildrenbuttheyareallcurrentlyrunning. pid_twaitpid(pid_tpid,int*stat_loc,intoptions):Similartowait()butallowsyoutowaitforaspecificprocessofgroupofprocesses,andallowsthespecificationofflagssuchaswnohang. wait3(.),wait4(.):Similartowait()butallowdifferentcombinationsofparametersandflags. inttcsetpgrp(intfildes,pid_tpgidjd):Setstheforegroundprocessgroupidtobetheforegroundgroupassociatedwiththecontrollingterminal.Thecontrollingterminalisusuallyassociatedwithstdin,stdout,andstderr(filedescriptorsO11,and2) intsetpgid(pid_tpid,pid_tpgid):SetstheprocessgroupIDoftheprocesswithIDpidtopgid. intdup2(intfiledes,intfiledes2):Causesthefiledescriptorfiledes2torefertothesamefileasfiledes.

    注意事项

    本文(Linux操作系统实验.docx)为本站会员(夺命阿水)主动上传,课桌文档仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知课桌文档(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    备案号:宁ICP备20000045号-1

    经营许可证:宁B2-20210002

    宁公网安备 64010402000986号

    课桌文档
    收起
    展开