unix考試資料打印版_第1頁
unix考試資料打印版_第2頁
unix考試資料打印版_第3頁
unix考試資料打印版_第4頁
unix考試資料打印版_第5頁
已閱讀5頁,還剩15頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

精選優(yōu)質(zhì)文檔-----傾情為你奉上精選優(yōu)質(zhì)文檔-----傾情為你奉上專心---專注---專業(yè)專心---專注---專業(yè)精選優(yōu)質(zhì)文檔-----傾情為你奉上專心---專注---專業(yè)2.1)ThestandardUnixprogramthatprovideson-linedocumentationiscalled中文:提供在線文檔的標(biāo)準的Unix程序被稱為BA.helpB.man2.2)TheUnixwhocommandshowsforeachlogged-inuserthe中文:Unix的命令顯示每個登錄用戶的AA.terminalname終端名稱B.officeaddress2.3)The-koptionoftheUnixmancommandisusedto中文:Unix的man命令的-k選項是用來BA.killfrozenconnectionsB.searchbykeyword按關(guān)鍵字搜索2.4)ThedatatypeUnixusestorecordloginrecordsiscalleda中文:數(shù)據(jù)類型的Unix用來記錄登錄記錄,被稱為AA.structutmp結(jié)構(gòu)的utmpB.structpwd2.5)Afiledescriptorisavalueoftype中文:文件描述符是一個()類型的值A(chǔ)A.intB.char*2.6)Thereadsystemcallindicatesendoffilebyreturningthevalue中文:read系統(tǒng)調(diào)用返回值()表示文件結(jié)束BA.-1B.02.7)Recordsintheutmpfileforactiveloginsessionshaveatypeof中文:活躍的登錄會話utmp文件中的記錄有一個()類型AA.USER_PROCESSB.LOGIN_PROCESS2.8)Openingafileforwriting中文:打開一個書面文件BA.erasesthecontentsofthefileB.setsthecurrentlocationtothestartofthefile設(shè)置當(dāng)前位置到文件的開頭2.9)Systemcallsaresaidtobeexpensivebecause中文:系統(tǒng)調(diào)用被指代價高由于AA.theyuseCPUtime他們使用的CPU時間B.computercenterschargeafeeforeachsystemcall2.10)Kernelbuffersarestored中文:內(nèi)核緩沖區(qū)存儲AA.incomputermemory在計算機內(nèi)存B.onharddisks2.11)Thelseeksystemcallallowsyouto中文:使用lseek系統(tǒng)調(diào)用允許你BA.searchforastringinafileB.changethecurrentread/writeposition改變當(dāng)前的讀/寫位置2.12)Unixsystemsrecordtimeasthenumberofsecondssince中文:Unix系統(tǒng)記錄()以來的秒數(shù)時間BA.January1,1900B.January1,19701970年1月1日起2.13)Itisillegaltolseek中文:在()使用lseek是非法的BA.afterthelastbyteinafileB.beforethefirstbyteinafile在一個文件中的第一個字節(jié)之前3.1)YoucanusethelscommandtolistfilesA中文:您可以使用ls命令在()列出文件A.inanydirectorytowhichyouhavereadaccess在任何您具有讀取權(quán)限的目錄B.onlyindirectoriesyouown3.2)Thelscommanddoesnotlistfileswithnamesbeginningwithadotbecause中文:ls命令不會列出以點開頭的文件名因為()AA.lsdoesnotlistthem不一一列舉B.thekernelassignsthosefilesa"hidden"attribute3.3)Tryingtousetheopensystemcallonadirectorywillfailif中文:如果()嘗試使用目錄中的open系統(tǒng)調(diào)用將失敗AA.youtrytoopenthedirectoryforwriting您嘗試打開用于寫入的目錄B.youarenotthesuperuser3.4)AUnixdirectorycontains中文:一個Unix目錄包含BA.namesandsizesoffilesB.namesandinodenumbersoffiles文件的名稱和inode號3.5)Thereaddirfunctionreturns中文:readdir函數(shù)返回BA.apointertothenameofafileB.apointertoastructdirent一個structdirent的指針3.6)Entriesinadirectoryare中文:目錄中的條目BA.sortedbydateoffilecreationB.notsorted沒有分類的3.7)Thestatsystemcallcantellyou中文:stat系統(tǒng)可以告訴你()BA.howmanypeoplehaveafileopenB.whoownsafile文件擁有者3.8)Abitmaskisusedfor中文:一個位掩碼是用于BA.protectingdatafromotherprocessesB.examiningpartsofanintegervalue研究一個整數(shù)值的部分3.9)Thest_ctimeattributeofafileindicates中文:st_ctime文件屬性指示BA.thelasttimefilecontentswerechangedB.thelasttimefileattributeswerechanged最后一次更改的文件屬性3.10)Theownerofafileisrecordedinastructstatas中文:文件的所有者是作為()記錄在一個stat結(jié)構(gòu)里BA.ausernamestringB.auseridnumber用戶ID號碼3.11)Aprogramwiththesetuseridbitsetwill中文:設(shè)置用戶ID位設(shè)置方案將會()BA.changetheusernameofthepersonrunningtheprogramB.runwiththeeffectiveuseridoftheowneroftheprogram運行程序的所有者的有效用戶ID3.12)Thetypeofafilecanbechanged中文:文件類型是可以被()改變的BA.onlybythesuperuserB.bynouser沒有用戶4.1)Apointertoafileiscalled中文:一個文件指針被稱為()BA.aninodeB.alink鏈接4.2)Thesizeofaninodetabledetermines中文:一個inode表的大小決定()BA.themaximumsizeofafileinthefilesystemB.themaximumnumberoffilesinthefilesystem在文件系統(tǒng)中的文件的最大數(shù)量4.3)Thesizeofthedataareaofafilesystemdetermines中文:文件系統(tǒng)的數(shù)據(jù)區(qū)的大小決定了()AA.themaximumspacefilesmayuseforstorage文件的可用于存儲的最大空間B.themaximumsizeofafileinthefilesystem4.4)Unixusesindirectblockstostore中文:Unix使用間接塊存儲AA.listsofblocknumbersofdatablocks列出數(shù)據(jù)塊的塊號B.symboliclinks4.5)Thecommand"ln..parent"failsbecause中文:命令“LN..parent”失敗,因為BA...isnotarealdirectoryB.UnixdoesnotallowuserstocreatelinkstodirectoriesUNIX不會允許用戶創(chuàng)建目錄的鏈接4.6)TheUnixcommandrmonlydeletesafileonlywhen中文:Unix命令RM只有當(dāng)()的時候只刪除文件BA.thesystemrunsoutoffreeblocksB.thelastlinkisremoved最后環(huán)節(jié)被移動4.7)Thechdirsystemcallchangesthe中文:CHDIR系統(tǒng)調(diào)用改變()AA.currentdirectoryofthecallingprocess調(diào)用進程的當(dāng)前目錄B.thenameof"."inthecurrentdirectory4.8)Thepwdcommandprintsthe中文:pwd命令打印AA.pathtothecurrentdirectory當(dāng)前目錄的路徑B.theinodenumberofthecurrentdirectory4.9)Adirectorymaynotbeusedasamountpointif中文:如果()該目錄將不能作為掛載點使用AA.thedirectorydoesnotexist目錄不存在B.thedirectoryisnotempty4.10)Unixdoesnotusedrivenamesinpathsbecause中文:Unix的路徑中不使用的驅(qū)動器名稱因為BA.thecolonisalegalcharacterinafilenameB.separatedisksaremountedassubdirectories單獨的磁盤作為子目錄被安裝4.11)Asymboliclinkmaybeusedtorefer中文:符號鏈接可能被用來指向()BA.onlytofilesonotherfilesystemsB.todirectories目錄6.1)Asoftwaretoolexpectstheterminaldrivertobein中文:一個軟件工具在()期望啟動終端驅(qū)動程序BA.canonicalprocessingmodeB.noparticularmode沒有特定的模式6.2)Canonicalprocessingmodeincludes中文:規(guī)范處理模式包括BA.bufferingandechoingB.bufferingandediting緩沖和編輯6.3)Iftheterminaldriverreceivestheerasekeywhileinnon-canonicalmodeit中文:當(dāng)在非規(guī)范模式如果終端驅(qū)動程序接收到擦除命令,它將會()BA.itdiscardsthecharacterB.passesthecharactertotheprogram傳遞字符到程序6.4)Auserprogrammaylimituserinputto'y'and'n'by中文:用戶程序可能會用()限制用戶輸入'Y'和'N'BA.tellingtheterminaldrivertodiscardallotherkeysB.ignoringallotherkeys忽略所有其他鍵6.5)Thereadsystemcall,usedonaterminalinnon-blockingmode中文:使用非阻塞模式的終端的read系統(tǒng)調(diào)用()AA.returns0ifnocharactersareavailable返回0在如果沒有可用的字符的情況下B.returns-1ifnocharactersareavailable6.6)Iftheterminaldriverreceivesakeywhileinnon-blockingmode,it中文:如果終端驅(qū)動程序在非阻塞模式下接收到一個命令,它將會()AA.storesthecharacteruntilaprogramcallsread存儲字符直到讀取一個程序調(diào)用B.discardsthecharacter6.7)Thesignalsystemcallisusedto中文:信號系統(tǒng)調(diào)用是用來AA.specifyaresponsetoaparticularsignal指定一個特別信號的響應(yīng)B.killaprocess6.8)Aprogrammaychangeitsresponsetoasignal中文:一個程序可能會改變其響應(yīng)信號AA.atanytime在任何時候B.onlyatthestartoftheprogram6.9)Aprogrammaychangetheinterruptkeybyusing中文:一個程序可能會用()改變使用中斷鍵BA.thesignalfunctionB.thetcsetattrfunctiontcsetattr功能6.10)Asynchronoussignalis中文:同步信號BA.generatedatascheduledtimeB.generatedinresponsetoaprogramoperation在響應(yīng)一個程序操作中形成8.1)Aprocessis中文:一個進程BA.asequenceofinstructionsacomputerexecutesB.memoryspaceanddatastructures內(nèi)存空間和數(shù)據(jù)結(jié)構(gòu)8.2)Aprocessisidentifiedby中文:一個程序通過()被識別BA.thenameoftheprogrambeingrunB.aninteger一個整數(shù)8.3)Ausercanlist中文:用戶可以列出BA.onlytheprocessesthatbelongtothatuserB.alltheprocessesrunningonthesystem系統(tǒng)上運行的所有進程8.4)Theexecvpsystemfunction中文:execvp系統(tǒng)的功能AA.runsaprograminthecallingprocess運行一個在調(diào)用進程的方案B.createsanewprocessandrunsaprogram8.5)Thearrayargumenttoexecvptellsthekernel中文:execvp數(shù)組參數(shù)告訴內(nèi)核AA.whatstringstopasstomaininthenewprogram哪些字符串傳遞到新的主程序B.whatlistofdirectoriestosearchtofindthenewprogram8.6)Theexecvpfunctionreturnsavalue中文:execvp函數(shù)返回一個值BA.onlyifitsuccessfullyrunstheprogramB.onlyifitfailstofindorruntheprogram只有當(dāng)它無法找到或運行程序8.7)Theforksystemcall中文:fork系統(tǒng)調(diào)用BA.createsanew,emptyprocessB.makesacopyofaprocess復(fù)制一個進程8.8)Theforksystemcallreturns0中文:fork系統(tǒng)調(diào)用返回0BA.whenthenewprocessfinishesB.inthenewprocess在新的進程8.9)Ashellrunsaprogramby中文:一個shell通過()運行一個程序AA.usingthesystemcallsforkandexec使用系統(tǒng)調(diào)用fork和execB.callingthelibraryfunctioncalled"system"8.10)Ifaprocesshasnochildprocesses,thewaitsystemcallreturns中文:如果一個進程沒有子進程,等待系統(tǒng)調(diào)用返回BA.0B.-18.11)Thewaitsystemcallsuspendsaprocessuntil中文:等待系統(tǒng)調(diào)用掛起進程直到BA.theuserpressesakeyB.achildprocessexitsoriskilled一個子進程退出或關(guān)閉8.12)Achildprocessreturnsavaluetoitsparentby中文:子進程通過()返回一個值給它的父進程AA.callingexit調(diào)用exitB.sendingasignal8.13)Thereturnvalueofthewaitsystemcallrepresents中文:等待系統(tǒng)調(diào)用的返回值表示AA.theprocessidnumberofachildthatisdone一個已完成的子進程的ID號B.theexitvalueofachildprocessthatisdone8.14)Achildcanuseexittoreturntoitsparentany中文:一個子進程可以使用退出返回到它的父進程AA.8-bitvalue8位值B.string10.1)TheUnixcommcommandisdesignedtocompare中文:設(shè)計Unixcomm命令的是要比較BA.anytwolistsofusernames任何兩個用戶名列表B.anytwosortedfiles任何兩個排序文件10.2)Ashellscriptcanstoredatainafilebyusing中文:一個shell腳本可以通過()在一個文件中存儲數(shù)據(jù)BA.the=assignmentoperator=賦值運算符B.the>redirectionoperatorthe>重定向操作符10.3)Theshellnotation"prog1|prog2"isarequestto中文:外殼符號“PROG1|PROG2”是一個()的請求AB.sendalloutputfromprog1tothestandardinputofprog2B.發(fā)送所有PROG1PROG2標(biāo)準輸入輸出10.4)Standardinputmeans中文:標(biāo)準輸入方式BA.thekeyboard鍵盤B.filedescriptor0文件描述符010.5)Theinputredirectionsymbol"<"isprocessedby中文:輸入重定向符號“<”通過()加工處理BA.theprogramthatreadsthedata讀取數(shù)據(jù)的程序B.theshell10.6)WhenUnixopensafile,itselectsanunusedfiledescriptor中文:UNIX打開一個文件時,它會選擇一個未使用的文件描述符和()AA.withthelowestvalue最低值B.thatwasclosedmostrecently最近被關(guān)閉10.7)Thedupsystemcallcopies中文:dup系統(tǒng)調(diào)用拷貝AA.anarrayentry數(shù)組項B.thecontentsofafile文件的內(nèi)容10.8)Thedup2systemcalldiffersfromdupinthatit中文:dup2系統(tǒng)調(diào)用與DUP不同在于它BA.makestwocopiesofafiledescriptor一個文件描述符的兩個副本B.isgivenaspecificdestinationforthecopy被給予一個特別的目的作為副本10.9)Theargumenttothepipesystemcallis中文:管道系統(tǒng)調(diào)用的參數(shù)BA.thesizeofthepipe管道的大小B.anarrayoftwointegers兩個整數(shù)的數(shù)組10.10)Whensettingupapipetoachild,theorderofsystemcallsis中文:當(dāng)設(shè)置一個管給子進程,系統(tǒng)調(diào)用的順序是BA.theparentcallsfork,thenbothprocessescallpipeA.父調(diào)用fork,然后兩個進程調(diào)用管B.theparentcallspipethencallsfork

B.父進程調(diào)用管,然后調(diào)用fork10.11)Connectionstoapiperemainineffectafterexecbecause中文:在EXEC后的鏈接管道仍然生效因為AA.thearrayofopenfilesispartoftheprocess,nottheprogramA打開的文件的陣列是進程中的一部分,而不是程序B.theparentaddsthepipetotheenvironmentB.父進程增加了對環(huán)境的管10.12)ThekernelsendsthesignalSIGPIPEtoaprocessthat中文:內(nèi)核發(fā)送信號SIGPIPE給一個()的進程BA.triestoreadfromapipewithaclosedwritingend

A.試圖從管道中讀取一個封閉的寫入結(jié)束B.triestowriteintoapipewithaclosedreadingendB.嘗試寫入一個封閉的讀端的管道結(jié)束10.13)Apipecanconnecttwochildrenofthesameprocessif中文:一個管道可以連接兩個相同的子進程如果()AA.theparentcreatesthepipebeforecreatingbothchildrenA.父進程在創(chuàng)建子進程之前創(chuàng)建這個管道B.theparentcreatestwopipesandconnectsthemB.父創(chuàng)建兩個管道,并將它們連接11.1)Thebc/dcpairofprogramsisanexampleof中文:程序BC/DC是一個()的例子BA.parallelprocessing并行處理B.client/serverdesign客戶機/服務(wù)器設(shè)計11.2)Youusethefunctionfdopeninsteadoffopento中文:您可以使用函數(shù)fdopen代替FOPEN為了()BA.redirectstandardinput重定向標(biāo)準輸入B.addstandardbufferingtoanopenfiledescriptorB.添加標(biāo)準緩沖到一個打開的文件描述符11.3)Youcannotusefopenforpipesbecause中文:你不可以向管道使用FOPEN是因為()AA.pipesdonothavefilenames管道沒有文件名B.pipeshavealimitedcapacity.管道的能力有限11.4)Ifaprocessthatreadsfromapipedoesnotclosethewritingend中文:如果一個從管道讀取的進程不關(guān)閉寫入結(jié)束()BA.thatprocesswillreceivetwocopiesofalldataA這一進程將收到所有數(shù)據(jù)的兩個副本B.thatprocesswillneverseeendoffileonthepipeB該進程將永遠不會看到在管道上的文件結(jié)束11.5)Apipecanbeusedtotransferdatabetween中文:管道可用于()之間傳輸數(shù)據(jù)BA.exactlytwoprocesses兩個進程B.anynumberofprocesses任意數(shù)量的進程11.6)Socketconnectionsaresimilartopipeconnectionsinthat中文:Socket連接和管道連接是相似處在于()BA.bothusetheirfiledescriptorsasaddresses都使用文件描述符作為地址B.processestransferdatathroughbothwiththereadandwritesystemcallsB.進程通過讀寫系統(tǒng)調(diào)用傳輸數(shù)據(jù)11.7)InUnixterminology,thedifferencebetweenahostandaserverisA中文:在Unix術(shù)語中,主機和服務(wù)器之間的區(qū)別A.aserverisprocess,ahostisacomputer服務(wù)器是一個進程,主機是一臺電腦B.aserverissmallercomputer,ahostsupportsmoreusers

B.服務(wù)器是小型計算機,一臺主機支持更多的用戶11.8)Aserverprogramusesthebindsystemcallto中文:服務(wù)器程序使用bind系統(tǒng)調(diào)用是為了()AA.attachanaddresstoitssocket附上一個地址給它的套接字B.lockthesocketinmemory鎖定內(nèi)存中的套接字11.9)Thelistensystemcallisusedto中文:聽系統(tǒng)調(diào)用是用來AA.enableincomingconnectionstoasocket啟用傳入連接到套接字B.receivedatafromaclient接收來自客戶端的數(shù)據(jù)11.10)Aclientprogrammakesaconnectiontoaserverprogrambycalling中文:一個客戶端程序通過()鏈接到一個服務(wù)器程序BA.socketB.connect連接11.11)Theprotocolforaclient/serverconnectiondescribes中文:客戶機/服務(wù)器連接的協(xié)議描述AA.theformatofthemessages消息的格式B.theformatofthesourcecode源代碼的格式11.12)Tolistfilesonaremotemachine,aclient中文:要列出遠程計算機上,客戶端BA.canpasstheservernametotheopendirsystemcall可以通過服務(wù)器的名稱opendir系統(tǒng)調(diào)用B.mustcontactaserverthatlistsfilesB.必須連接上一個列舉文件的服務(wù)器11.13)Theproblemwithusingthepopenfunctioninserversis中文:在服務(wù)器上使用popen函數(shù)的問題AA.popencanrunarbitraryshellcommandsA.POPEN可以執(zhí)行任意shell命令B.theserverhastocallthepclosefunctiontopreventzombies

B.服務(wù)器不得不調(diào)用pclose函數(shù)的功能以防止僵尸模式13.1)Softwarevendorsprovidehardwarekeysto中文:軟件供應(yīng)商提供硬件鍵是為了()BA.protectuserdatafromintruders保護用戶數(shù)據(jù)免受入侵者B.preventunauthorizeduseoftheirprogramsB.防止未經(jīng)授權(quán)使用他們的方案13.2)Managingcompanycarsissimilartomanagingsoftwarelicensesbecause中文:管理公司車輛類似于管理軟件許可證,是因為()AA.bothinvolvesharingafixednumberofitemsamongseveralusersA都涉及多個用戶之間共享一個固定數(shù)量的物品B.youhavetopayforanewoneincaseofacrashB.你不得不為一個新的而付出代價如果發(fā)生碰撞13.3)Themajordifferencebetweendatagramsocketsandstreamsocketsis中文:數(shù)據(jù)報套接字和流式套接字之間的主要區(qū)別在于AA.datagramsocketsarenotconnected數(shù)據(jù)報套接字沒有連接B.streamsocketsarenotreliable流套接字是不可靠的13.4)Anadvantageofdatagramsocketsoverstreamsocketsis中文:數(shù)據(jù)報套接字相對于流套接字的優(yōu)點是BA.theydonotrequiresocketaddresses他們不要求套接字地址B.theyrequirelessworkfromthenetworksoftwareB.他們需要更少來自網(wǎng)絡(luò)軟件的工作13.5)Aserverusestheaddressargumenttotherecvfromsystemcallto中文:服務(wù)器使用recvfrom系統(tǒng)調(diào)用的地址參數(shù)是為了()BA.specifywhichclientsmaysenditmessages指定客戶端可能發(fā)送郵件B.betoldwhichclientsentamessage被告訴哪個客戶端發(fā)送了消息13.6)Thesendtosystemcalldoesnotuseareturnaddressargument中文:在SendTo系統(tǒng)調(diào)用不使用返回地址參數(shù)AA.becausethenetworksoftwareaddstheaddressofthesocketA因為網(wǎng)絡(luò)軟件添加了套接字地址B.sosomeclientscanremainanonymous

B.為了有些客戶端可以保持匿名13.7)Datagramsocketswouldbeagoodchoicefortransmitting中文:數(shù)據(jù)報套接字將是一個不錯的傳輸()的選擇BA.automatedtellermachinetransactions自動取款機交易B.backgroundmusicforelevators電梯背景音樂13.8)Theclientshouldchecktheaddressinthedo_transactionfunction中文:客戶端應(yīng)檢查在do_transaction函數(shù)的地址BA.tomakesurethedatagramiscomplete要確保數(shù)據(jù)報是完整的B.tomakesurethedatagramcomesfromtheserverB為了確保數(shù)據(jù)報來自服務(wù)器13.9)Ifaclientcrashesbeforeitreturnsitsticket中文:如果客戶端在返回標(biāo)簽之前崩潰AA.theserverwillhaveanincorrectcountofrunningprogramsA服務(wù)器將有一個正在運行的錯誤程序的統(tǒng)計B.theserverwillreceiveSIGCHLDB.服務(wù)器將收到SIGCHLD13.10)Theserverchecksifaclientisstillactiveby中文:服務(wù)器檢查通過()檢查客戶端是否仍活躍BA.sendingadatagramtotheclient發(fā)送一個數(shù)據(jù)包到客戶端B.sendingsignal0totheclient向客戶端發(fā)送信號013.11)Aclientcannotgiveitstickettoanotherprocessbecause中文:一個客戶端不能給予其標(biāo)簽到另一個進程是因為AA.theprotocolspecifiesthatclientstalkonlytotheserverA協(xié)議規(guī)定客戶端只和服務(wù)器端通話B.aprocessmayonlysenddatagramstoarelatedprocessB.一個進程可能只有數(shù)據(jù)報發(fā)送到一個相關(guān)的過程13.12)Ticketvalidationisatechniqueusedto中文:票務(wù)驗證是一種用于()的技術(shù)BA.preventclientsfromcrashing防止客戶端崩潰B.recoverdataiftheservercrashes當(dāng)服務(wù)器崩潰的時候恢復(fù)數(shù)據(jù)13.13)AsocketwithanaddressintheUnixdomain中文:在Unix域的地址套接字BA.canbereachedbyclientsonanyUnixmachine可以由客戶在任何Unix機器上達到B.canonlybereachedbyclientsonthesamemachineB.只能由同一臺機器上的客戶達成Shell用fork建立新進程,用exec在新進程中運行用戶指定的程序,最后shell用wait等待新進程結(jié)束。Wait系統(tǒng)調(diào)用同時從內(nèi)核取得退出狀態(tài)或者信號序號以告知子進程是如何結(jié)束。每個unixshell都是使用下圖所示的模型。現(xiàn)在將3個系統(tǒng)調(diào)用組合在一起實現(xiàn)一個真正的shell。P250psh2.c實現(xiàn)一個shell:psh2.c下圖是unixshell的簡化流程圖。Psh2.c將使用這流程。代碼如下:/**promptingshellversion2**** Solvesthe`one-shot'problemofversion1** Usesexecvp(),butfork()sfirstsothatthe** shellwaitsaroundtoperformanothercommand** Newproblem:shellcatchessignals.Runvi,press^c.**/#include <stdio.h>#include <signal.h>#define MAXARGS 20 /*cmdlineargs */#define ARGLEN 100 /*tokenlength */main(){ char *arglist[MAXARGS+1]; /*anarrayofptrs */ int numargs; /*indexintoarray */ char argbuf[ARGLEN]; /*readstuffhere */ char *makestring(); /*mallocetc */ numargs=0; while(numargs<MAXARGS) { printf("Arg[%d]?",numargs); if(fgets(argbuf,ARGLEN,stdin)&&*argbuf!='\n') arglist[numargs++]=makestring(argbuf); else { if(numargs>0){ /*anyargs? */ arglist[numargs]=NULL; /*closelist */ execute(arglist); /*doit */ numargs=0; /*andreset */ } } } return0;}execute(char*arglist[])/** useforkandexecvpandwaittodoit*/{ int pid,exitstatus; /*ofchild */ pid=fork(); /*makenewprocess*/ switch(pid){ case-1: perror("forkfailed"); exit(1); case0: execvp(arglist[0],arglist); /*doit*/ perror("execvpfailed"); exit(1); default: while(wait(&exitstatus)!=pid) ; printf("childexitedwithstatus%d,%d\n", exitstatus>>8,exitstatus&0377); }}char*makestring(char*buf)/**trimoffnewlineandcreatestorageforthestring*/{ char *cp,*malloc(); buf[strlen(buf)-1]='\0'; /*trimnewline */ cp=malloc(strlen(buf)+1); /*getmemory */ if(cp==NULL){ /*ordie */ fprintf(stderr,"nomemory\n"); exit(1); } strcpy(cp,buf); /*copychars */ returncp; /*returnptr */}P319pipe.c編寫一個通用的程序pipe(管道)(管道編程)它使用兩個程序的名字做參數(shù),:例如:PipewhosortPipeIshead程序的內(nèi)在邏輯如下所示:代碼如下:/*pipe.c * *Demonstrateshowtocreateapipelinefromoneprocesstoanother* *Takestwoargs,eachacommand,andconnects* av[1]'soutputtoinputofav[2]* *usage:pipecommand1command2* effect:command1|command2* *Limitations:commandsdonottakearguments* *usesexeclp()sinceknownnumberofargs* *Note:exchangechildandparentandwatchfun*/#include <stdio.h>#include <unistd.h>#define oops(m,x) {perror(m);exit(x);}main(intac,char**av){ int thepipe[2], /*twofiledescriptors */ newfd, /*usefulforpipes */ pid; /*andthepid */ if(ac!=3){ fprintf(stderr,"usage:pipecmd1cmd2\n"); exit(1); } if(pipe(thepipe)==-1) /*getapipe */ oops("Cannotgetapipe",1); /*------------------------------------------------------------*/ /* nowwehaveapipe,nowlet'sgettwoprocesses */ if((pid=fork())==-1) /*getaproc */ oops("Cannotfork",2); /*------------------------------------------------------------*/ /* RightHere,therearetwoprocesses */ /*parentwillreadfrompipe */ if(pid>0){ /*parentwillexecav[2] */ close(thepipe[1]); /*parentdoesn'twritetopipe */ if(dup2(thepipe[0],0)==-1) oops("couldnotredirectstdin",3); close(thepipe[0]); /*stdinisduped,closepipe */ execlp(av[2],av[2],NULL); oops(av[2],4); } /* childexecsav[1]andwritesintopipe */ close(thepipe[0]); /*childdoesn'treadfrompipe */ if(dup2(thepipe[1],1)==-1) oops("couldnotredirectstdout",4); close(thepipe[1]); /*stdoutisduped,closepipe */ execlp(av[1],av[1],NULL); oops(av[1],5);}P335popen.c實現(xiàn)popen:使用fdopen命令(讓進程看似文件)Popen運行一個程序并返回指向該程序標(biāo)準輸入或標(biāo)準輸出的連接。這里合并了pipe、fork、dup2和exec等系統(tǒng)調(diào)用,其流程如下:代碼如下:/*popen.c-aversionoftheUnixpopen()libraryfunction* FILE*popen(char*command,char*mode)* commandisaregularshellcommand* modeis"r"or"w"* returnsastreamattachedtothecommand,orNULL* execls"sh""-c"command*todo:whataboutsignalhandlingforchildprocess?*/#include <stdio.h>#include <signal.h>#define READ 0#define WRITE 1main(){ FILE *fp; char buf[BUFSIZ]; fp=popen("ls","r"); while(fgets(buf,BUFSIZ,fp)!=NULL) fputs(buf,stdout);}FILE*popen(constchar*command,constchar*mode){ int pfp[2],pid; /*thepipeandtheprocess */ FILE *fdopen(),*fp; /*fdopenmakesafdastream */ int parent_end,child_end; /*ofpipe */ if(*mode=='r'){ /*figureoutdirection */ parent_end=READ; child_end=WRITE; }elseif(*mode=='w'){ parent_end=WRITE; child_end=READ; }elsereturnNULL; if(pipe(pfp)==-1) /*getapipe */ returnNULL; if((pid=fork())==-1){ /*andaprocess */ close(pfp[0]); /*ordisposeofpipe */ close(pfp[1]); returnNULL; } /*---------------parentcodehere-------------------*/ /*needtocloseoneendandfdopenotherend */ if(pid>0){ if(close(pfp[child_end])==-1) returnNULL; returnfdopen(pfp[parent_end],mode); /*samemode*/ } /*---------------childcodehere---------------------*/ /*needtoredirectstdinorstdoutthenexecthecmd */ if(close(pfp[parent_end])==-1) /*closetheotherend */ exit(1); /*doNOTreturn */ if(dup2(pfp[child_end],child_end)==-1) exit(1); if(close(pfp[child_end])==-1) /*donewiththisone */ exit(1); /*allsettoruncmd */ execl("/bin/sh","sh","-c",command,NULL); exit(1);}P353rlsd.c服務(wù)器程序:rlsd(遠程Is系統(tǒng))服務(wù)器必須得到一個socket,然后調(diào)用bind、listen命令,最后調(diào)用accept來接受一次呼叫。在接受呼叫后,服務(wù)器從socket讀取目錄后,列出目錄下得內(nèi)容。下面代碼使用了popen如下:/*rlsd.c-aremotelsserver-withparanoia*/#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/in.h>#include<netdb.h>#include<time.h>#include<strings.h>#definePORTNUM15000/*ourremotelsserverport*/#defineHOSTLEN256#defineoops(msg){perror(msg);exit(1);}intmain(intac,char*av[]){ structsockaddr_insaddr;/*buildouraddresshere*/ struct hostent *hp;/*thisispartofour*/ char hostname[HOSTLEN];/*address */ int sock_id,sock_fd;/*lineid,filedesc*/ FILE *sock_fpi,*sock_fpo;/*streamsforinandout*/ FILE *pipe_fp; /*usepopentorunls*/ chardirname[BUFSIZ];/*fromclient*/ charcommand[BUFSIZ];/*forpopen()*/ int dirlen,c;/**Step1:askkernelforasocket**/ sock_id=socket(PF_INET,SOCK_STREAM,0);/*getasocket*/ if(sock_id==-1) oops("socket");/**Step2:bindaddresstosocket.Addressishost,port**/ bzero((void*)&saddr,sizeof(saddr));/*clearoutstruct*/ gethostname(hostname,HOSTLEN);/*whereamI?*/ hp=gethostbyname(hostname);/*getinfoabouthost*/ bcopy((void*)hp->h_addr,(void*)&saddr.sin_addr,hp->h_length); saddr.sin_port=htons(PORTNUM);/*fillinsocketport*/ saddr.sin_family=AF_INET;/*fillinaddrfamily*/ if(bind(sock_id,(structsockaddr*)&saddr,sizeof(saddr))!=0) oops("bind");/**Step3:allowincomingcallswithQsize=1onsocket**/ if(listen(sock_id,1)!=0) oops("listen");/**mainloop:accept(),write(),close()*/ while(1){ sock_fd=accept(sock_id,NULL,NULL);/*waitforcall*/ if(sock_fd==-1) oops("accept"); /*openreadingdirectionasbufferedstream*/ if((sock_fpi=fdopen(sock_fd,"r"))==NULL) oops("fdopenreading"); if(fgets(dirname,BUFSIZ-5,sock_fpi)==NULL) oops("readingdirname"); sanitize(dirname); /*openwritingdirectionasbufferedstream*/ if((sock_fpo=fdopen(sock_fd,"w"))==NULL) oops("fdopenwriting"); sprintf(command,"ls%s",dirname); if((pipe_fp=popen(command,"r"))==NULL) oops("popen"); /*transferdatafromlstosocket*/ while((c=getc(pipe_fp))!=EOF) putc(c,sock_fpo); pclose(pipe_fp); fclose(sock_fpo); fclose(sock_fpi);}}sanitize(char*str)/**itwouldbeverybadifsomeonepassedusandirnamelike*";rm*"andwenaivelycreatedacommand"ls;rm*"**so..weremoveeverythingbutslashesandalphanumerics*Therearenicersolutions,seeexercises*/{ char*src,*dest; for(src=dest=str;*src;src++) if(*src=='/'||isalnum(*src)) *dest++=*src; *dest='\0';}P432twordcount2.c版本2:兩個線程、一個計數(shù)器、一個互斥量。共享一個計數(shù)器。(線程間的分工合作)線程系統(tǒng)包含了稱為互斥鎖的變量,它可以使線程間很好的合作,避免資源訪問的沖突。如何創(chuàng)建和使用互斥量——代碼如下:/*twordcount2.c-threadedwordcounterfortwofiles. *//*version2:usesmutextolockcounter*/#include<stdio.h>#include<pthread.h>#include<ctype.h>int total_words;/*thecounteranditslock*/pthread_mutex_tcounter_lock=PTHREAD_MUTEX_INITIALIZER;main(intac,char*av[]){ pthread_tt1,t2; /*twothreads*/ void *count_words(void*); if(ac!=3){ printf("usage:%sfile1file2\n",av[0]); exit(1); } total_words=0; pthread_create(&t1,NULL,count_words,(void*)av[1]); pthread_create(&t2,NULL,count_words,(void*)av[2]); pthread_join(t1,NULL); pthread_join(t2,NULL); printf("%5d:totalwords\n",total_words);}void*count_words(void*f){ char*filename=(char*)f; FILE*fp; intc,prevc='\0'; if((fp=fopen(filename,"r"))!=NULL){ while((c=getc(fp))!=EOF){ if(!isalnum(c)&&isalnum(prevc)){ pthread_mutex_lock(&counter_lock); total_words++; pthread_mutex_unlock(&counter_lock); } prevc=c; } fclose(fp); }else perror(filename); returnNULL;}P435twordcount3.c版本3:兩個線程、兩個計數(shù)器、向線程傳遞多個參數(shù)(線程間的分工合作)字數(shù)的統(tǒng)計程序為每個線程設(shè)置自己的計數(shù)器,當(dāng)線程返回后,再將這兩個計數(shù)器的值加起來得到最后的結(jié)果。代碼如下:/*twordcount3.c-threadedwordcounterfortwofiles. * -Version3:onecounterperfile*/#include<stdio.h>#include<pthread.h>#include<ctype.h>structarg_set{ /*twovaluesinonearg*/ char*fname; /*filetoexamine */ intcount; /*numberofwords */};main(intac,char*av[]){ pth

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論