/
5InterludeProcessAPI 5InterludeProcessAPI

5InterludeProcessAPI - PDF document

samantha
samantha . @samantha
Follow
343 views
Uploaded On 2021-10-07

5InterludeProcessAPI - PPT Presentation

ASIDEINTERLUDESInterludeswillcovermorepracticalaspectsofsystemsincludingaparticularfocusonoperatingsystemAPIsandhowtousethemIfyoudontlikepracticalthingsyoucouldskiptheseinterludesButyoushouldlikeprac ID: 897046

wait pid prompt fork pid wait fork prompt forexample int getpid processapi rst interlude org iamchild ostep arpaci www

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "5InterludeProcessAPI" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1 5Interlude:ProcessAPI ASIDE:INTERLUDESIn
5Interlude:ProcessAPI ASIDE:INTERLUDESInterludeswillcovermorepracticalaspectsofsystems,includingapar-ticularfocusonoperatingsystemAPIsandhowtousethem.Ifyoudon'tlikepracticalthings,youcouldskiptheseinterludes.Butyoushouldlikepracticalthings,because,well,theyaregenerallyusefulinreallife;com-panies,forexample,don'tusuallyhireyouforyournon-practicalskills.Inthisinterlude,wediscussprocesscreationinUNIXsystems.UNIXpresentsoneofthemostintriguingwaystocreateanewprocesswithapairofsystemcalls:fork()andexec().Athirdroutine,wait(),canbeusedbyaprocesswishingtowaitforaprocessithascreatedtocomplete.Wenowpresenttheseinterfacesinmoredetail,withafewsimpleexamplestomotivateus.Andthus,ourproblem: CRUX:HOWTOCREATEANDCONTROLPROCESSESWhatinterfacesshouldtheOSpresentforprocesscreationandcon-trol?Howshouldtheseinterfacesbedesignedtoenablepowerfulfunc-tionality,easeofuse,andhighperformance?5.1Thefork()SystemCallThefork()systemcallisusedtocreateanewprocess[C63].How-ever,beforewarned:itiscertainlythestrangestroutineyouwillevercall1.Morespecically,youhavearunningprogramwhosecodelookslikewhatyouseeinFigure5.1;examinethecode,orbetteryet,typeitinandrunityourself! 1Well,OK,weadmitthatwedon'tknowthatforsure;whoknowswhatroutinesyoucallwhennooneislooking?Butfork()isprettyodd,nomatterhowunusualyourroutine-callingpatternsare.1 2INTERLUDE:PROCESSAPI 1#includestdio.h&#x-0.2;䈳 2#includestdlib.h&#x-0.2;䈳 3#includeunistd.h&#x-0.2;䈳 45intmain(intargc,char*argv[]){6printf("helloworld(pid:%d)\n",(int)getpid());7intrc=fork();8if(rc0){9//forkfailed10fprintf(stderr,"forkfailed\n");11exit(1);12}elseif(rc==0){13//child(newprocess)14printf("hello,Iamchild(pid:%d)\n",(int)getpid());15}else{16//parentgoesdownthispath(main)17printf("hello,Iamparentof%d(pid:%d

2 )\n",18rc,(int)getpid());19}20return0;21
)\n",18rc,(int)getpid());19}20return0;21}22Figure5.1:Callingfork()(p1.c)Whenyourunthisprogram(calledp1.c),you'llseethefollowing:prompt&#x-599;&#x.490;./p1helloworld(pid:29146)hello,Iamparentof29147(pid:29146)hello,Iamchild(pid:29147)prompt&#x-599;&#x.490;Letusunderstandwhathappenedinmoredetailinp1.c.Whenitrststartedrunning,theprocessprintsoutahelloworldmessage;in-cludedinthatmessageisitsprocessidentier,alsoknownasaPID.TheprocesshasaPIDof29146;inUNIXsystems,thePIDisusedtonametheprocessifonewantstodosomethingwiththeprocess,suchas(forexample)stopitfromrunning.Sofar,sogood.Nowtheinterestingpartbegins.Theprocesscallsthefork()systemcall,whichtheOSprovidesasawaytocreateanewprocess.Theoddpart:theprocessthatiscreatedisan(almost)exactcopyofthecallingpro-cess.ThatmeansthattotheOS,itnowlooksliketherearetwocopiesoftheprogramp1running,andbothareabouttoreturnfromthefork()systemcall.Thenewly-createdprocess(calledthechild,incontrasttothecreatingparent)doesn'tstartrunningatmain(),likeyoumightexpect(note,the“hello,world”messageonlygotprintedoutonce);rather,itjustcomesintolifeasifithadcalledfork()itself.OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG INTERLUDE:PROCESSAPI3 1#includestdio.h&#x-0.2;䈳 2#includestdlib.h&#x-0.2;䈳 3#includeunistd.h&#x-0.2;䈳 4#includesys/wait.h&#x-0.2;䈳 56intmain(intargc,char*argv[]){7printf("helloworld(pid:%d)\n",(int)getpid());8intrc=fork();9if(rc0){//forkfailed;exit10fprintf(stderr,"forkfailed\n");11exit(1);12}elseif(rc==0){//child(newprocess)13printf("hello,Iamchild(pid:%d)\n",(int)getpid());14}else{//parentgoesdownthispath(main)15intrc_wait=wait(NULL);16printf("hello,Iamparentof%d(rc_wait:%d)(pid:%d)\n",17rc,rc_wait,(int)getpid());18}19return0;20}21Figure5.2:Callingfork()Andwait()(p2.c)Youmighth

3 avenoticed:thechildisn'tanexactcopy.Spec
avenoticed:thechildisn'tanexactcopy.Specically,al-thoughitnowhasitsowncopyoftheaddressspace(i.e.,itsownprivatememory),itsownregisters,itsownPC,andsoforth,thevalueitreturnstothecalleroffork()isdifferent.Specically,whiletheparentreceivesthePIDofthenewly-createdchild,thechildreceivesareturncodeofzero.Thisdifferentiationisuseful,becauseitissimplethentowritethecodethathandlesthetwodifferentcases(asabove).Youmightalsohavenoticed:theoutput(ofp1.c)isnotdeterministic.Whenthechildprocessiscreated,therearenowtwoactiveprocessesinthesystemthatwecareabout:theparentandthechild.AssumingwearerunningonasystemwithasingleCPU(forsimplicity),theneitherthechildortheparentmightrunatthatpoint.Inourexample(above),theparentdidandthusprintedoutitsmessagerst.Inothercases,theoppositemighthappen,asweshowinthisoutputtrace:prompt&#x-600;&#x.492;./p1helloworld(pid:29146)hello,Iamchild(pid:29147)hello,Iamparentof29147(pid:29146)prompt&#x-600;&#x.492;TheCPUscheduler,atopicwe'lldiscussingreatdetailsoon,deter-mineswhichprocessrunsatagivenmomentintime;becausethesched-uleriscomplex,wecannotusuallymakestrongassumptionsaboutwhatc\r2008–20,ARPACI-DUSSEAUTHREEEASYPIECES 4INTERLUDE:PROCESSAPI itwillchoosetodo,andhencewhichprocesswillrunrst.Thisnon-determinism,asitturnsout,leadstosomeinterestingproblems,par-ticularlyinmulti-threadedprograms;hence,we'llseealotmorenon-determinismwhenwestudyconcurrencyinthesecondpartofthebook.5.2Thewait()SystemCallSofar,wehaven'tdonemuch:justcreatedachildthatprintsoutamessageandexits.Sometimes,asitturnsout,itisquiteusefulforaparenttowaitforachildprocesstonishwhatithasbeendoing.Thistaskisaccomplishedwiththewait()systemcall(oritsmorecompletesiblingwaitpid());seeFigure5.2fordetails.Inthisexample(p2.c),theparentprocesscallswait()to

4 delayitsexecutionuntilthechildnishesexe
delayitsexecutionuntilthechildnishesexecuting.Whenthechildisdone,wait()returnstotheparent.Addingawait()calltothecodeabovemakestheoutputdetermin-istic.Canyouseewhy?Goahead,thinkaboutit.(waitingforyoutothink....anddone)Nowthatyouhavethoughtabit,hereistheoutput:prompt�./p2helloworld(pid:29266)hello,Iamchild(pid:29267)hello,Iamparentof29267(rc_wait:29267)(pid:29266)prompt�Withthiscode,wenowknowthatthechildwillalwaysprintrst.Whydoweknowthat?Well,itmightsimplyrunrst,asbefore,andthusprintbeforetheparent.However,iftheparentdoeshappentorunrst,itwillimmediatelycallwait();thissystemcallwon'treturnuntilthechildhasrunandexited2.Thus,evenwhentheparentrunsrst,itpolitelywaitsforthechildtonishrunning,thenwait()returns,andthentheparentprintsitsmessage.5.3Finally,Theexec()SystemCallAnalandimportantpieceoftheprocesscreationAPIistheexec()systemcall3.Thissystemcallisusefulwhenyouwanttorunaprogramthatisdifferentfromthecallingprogram.Forexample,callingfork() 2Thereareafewcaseswherewait()returnsbeforethechildexits;readthemanpageformoredetails,asalways.Andbewareofanyabsoluteandunqualiedstatementsthisbookmakes,suchas“thechildwillalwaysprintrst”or“UNIXisthebestthingintheworld,evenbetterthanicecream.”3OnLinux,therearesixvariantsofexec():execl,execlp(),execle(),execv(),execvp(),andexecvpe().Readthemanpagestolearnmore.OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG INTERLUDE:PROCESSAPI5 1#includestdio.h&#x-0.2;䈳 2#includestdlib.h&#x-0.2;䈳 3#includeunistd.h&#x-0.2;䈳 4#includestring.h&#x-0.2;䈳 5#includesys/wait.h&#x-0.2;䈳 67intmain(intargc,char*argv[]){8printf("helloworld(pid:%d)\n",(int)getpid());9intrc=fork();10if(rc0){//forkfailed;exit11fprintf(stderr,"forkfailed\n");12exit(1);13}elseif(rc==0){//child(newproces

5 s)14printf("hello,Iamchild(pid:%d)\n",(i
s)14printf("hello,Iamchild(pid:%d)\n",(int)getpid());15char*myargs[3];16myargs[0]=strdup("wc");//program:"wc"(wordcount)17myargs[1]=strdup("p3.c");//argument:filetocount18myargs[2]=NULL;//marksendofarray19execvp(myargs[0],myargs);//runswordcount20printf("thisshouldn'tprintout");21}else{//parentgoesdownthispath(main)22intrc_wait=wait(NULL);23printf("hello,Iamparentof%d(rc_wait:%d)(pid:%d)\n",24rc,rc_wait,(int)getpid());25}26return0;27}28Figure5.3:Callingfork(),wait(),Andexec()(p3.c)inp2.cisonlyusefulifyouwanttokeeprunningcopiesofthesameprogram.However,oftenyouwanttorunadifferentprogram;exec()doesjustthat(Figure5.3).Inthisexample,thechildprocesscallsexecvp()inordertoruntheprogramwc,whichisthewordcountingprogram.Infact,itrunswconthesourcelep3.c,thustellingushowmanylines,words,andbytesarefoundinthele:prompt&#x-600;&#x.492;./p3helloworld(pid:29383)hello,Iamchild(pid:29384)291071030p3.chello,Iamparentof29384(rc_wait:29384)(pid:29383)prompt&#x-600;&#x.492;Thefork()systemcallisstrange;itspartnerincrime,exec(),isnotsonormaleither.Whatitdoes:giventhenameofanexecutable(e.g.,wc),andsomearguments(e.g.,p3.c),itloadscode(andstaticdata)fromthatc\r2008–20,ARPACI-DUSSEAUTHREEEASYPIECES 6INTERLUDE:PROCESSAPI TIP:GETTINGITRIGHT(LAMPSONSLAW)AsLampsonstatesinhiswell-regarded“HintsforComputerSystemsDesign”[L83],“Getitright.Neitherabstractionnorsimplicityisasub-stituteforgettingitright.”Sometimes,youjusthavetodotherightthing,andwhenyoudo,itiswaybetterthanthealternatives.TherearelotsofwaystodesignAPIsforprocesscreation;however,thecombinationoffork()andexec()aresimpleandimmenselypowerful.Here,theUNIXdesignerssimplygotitright.AndbecauseLampsonsooften“gotitright”,wenamethelawinhishonor.executableandoverwritesitscurrentcodesegment(andcurrentsta

6 ticdata)withit;theheapandstackandotherpa
ticdata)withit;theheapandstackandotherpartsofthememoryspaceoftheprogramarere-initialized.ThentheOSsimplyrunsthatprogram,passinginanyargumentsastheargvofthatprocess.Thus,itdoesnotcreateanewprocess;rather,ittransformsthecurrentlyrunningprogram(formerlyp3)intoadifferentrunningprogram(wc).Aftertheexec()inthechild,itisalmostasifp3.cneverran;asuccessfulcalltoexec()neverreturns.5.4Why?MotivatingTheAPIOfcourse,onebigquestionyoumighthave:whywouldwebuildsuchanoddinterfacetowhatshouldbethesimpleactofcreatinganewprocess?Well,asitturnsout,theseparationoffork()andexec()isessentialinbuildingaUNIXshell,becauseitletstheshellruncodeafterthecalltofork()butbeforethecalltoexec();thiscodecanaltertheenvironmentoftheabout-to-be-runprogram,andthusenablesavarietyofinterestingfeaturestobereadilybuilt.Theshellisjustauserprogram4.Itshowsyouapromptandthenwaitsforyoutotypesomethingintoit.Youthentypeacommand(i.e.,thenameofanexecutableprogram,plusanyarguments)intoit;inmostcases,theshellthenguresoutwhereinthelesystemtheexecutableresides,callsfork()tocreateanewchildprocesstorunthecommand,callssomevariantofexec()torunthecommand,andthenwaitsforthecommandtocompletebycallingwait().Whenthechildcompletes,theshellreturnsfromwait()andprintsoutapromptagain,readyforyournextcommand.Theseparationoffork()andexec()allowstheshelltodoawholebunchofusefulthingsrathereasily.Forexample:prompt�wcp3.c�newfile.txt 4Andtherearelotsofshells;tcsh,bash,andzshtonameafew.Youshouldpickone,readitsmanpages,andlearnmoreaboutit;allUNIXexpertsdo.OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG INTERLUDE:PROCESSAPI7 Intheexampleabove,theoutputoftheprogramwcisredirectedintotheoutputlenewfile.txt(thegreater-thansignishowsaidredirec-tionisindicated).Thewaytheshellaccomplishesthist

7 askisquitesim-ple:whenthechildiscreated,
askisquitesim-ple:whenthechildiscreated,beforecallingexec(),theshellclosesstandardoutputandopensthelenewfile.txt.Bydoingso,anyout-putfromthesoon-to-be-runningprogramwcaresenttotheleinsteadofthescreen.Figure5.4(page8)showsaprogramthatdoesexactlythis.Thereasonthisredirectionworksisduetoanassumptionabouthowtheoperatingsystemmanagesledescriptors.Specically,UNIXsystemsstartlookingforfreeledescriptorsatzero.Inthiscase,STDOUT FILENOwillbetherstavailableoneandthusgetassignedwhenopen()iscalled.Subse-quentwritesbythechildprocesstothestandardoutputledescriptor,forexamplebyroutinessuchasprintf(),willthenberoutedtranspar-entlytothenewly-openedleinsteadofthescreen.Hereistheoutputofrunningthep4.cprogram:prompt�./p4prompt�catp4.output32109846p4.cprompt�You'llnotice(atleast)twointerestingtidbitsaboutthisoutput.First,whenp4isrun,itlooksasifnothinghashappened;theshelljustprintsthecommandpromptandisimmediatelyreadyforyournextcommand.However,thatisnotthecase;theprogramp4didindeedcallfork()tocreateanewchild,andthenrunthewcprogramviaacalltoexecvp().Youdon'tseeanyoutputprintedtothescreenbecauseithasbeenredi-rectedtothelep4.output.Second,youcanseethatwhenwecattheoutputle,alltheexpectedoutputfromrunningwcisfound.Cool,right?UNIXpipesareimplementedinasimilarway,butwiththepipe()systemcall.Inthiscase,theoutputofoneprocessisconnectedtoanin-kernelpipe(i.e.,queue),andtheinputofanotherprocessisconnectedtothatsamepipe;thus,theoutputofoneprocessseamlesslyisusedasinputtothenext,andlongandusefulchainsofcommandscanbestrungtogether.Asasimpleexample,considerlookingforawordinale,andthencountinghowmanytimessaidwordoccurs;withpipesandtheutil-itiesgrepandwc,itiseasy;justtypegrep-ofoofile|wc-lintothecommandpromptandmarvelattheresul

8 t.Finally,whilewejusthavesketchedoutthep
t.Finally,whilewejusthavesketchedouttheprocessAPIatahighlevel,thereisalotmoredetailaboutthesecallsouttheretobelearnedanddigested;we'lllearnmore,forexample,aboutledescriptorswhenwetalkaboutlesystemsinthethirdpartofthebook.Fornow,sufceittosaythatthefork()/exec()combinationisapowerfulwaytocreateandmanipulateprocesses.c\r2008–20,ARPACI-DUSSEAUTHREEEASYPIECES 8INTERLUDE:PROCESSAPI 1#includestdio.h&#x-0.2;䈳 2#includestdlib.h&#x-0.2;䈳 3#includeunistd.h&#x-0.2;䈳 4#includestring.h&#x-0.2;䈳 5#includefcntl.h&#x-0.2;䈳 6#includesys/wait.h&#x-0.2;䈳 78intmain(intargc,char*argv[]){9intrc=fork();10if(rc0){11//forkfailed12fprintf(stderr,"forkfailed\n");13exit(1);14}elseif(rc==0){15//child:redirectstandardoutputtoafile16close(STDOUT_FILENO);17open("./p4.output",O_CREAT|O_WRONLY|O_TRUNC,S_IRWXU);1819//nowexec"wc"...20char*myargs[3];21myargs[0]=strdup("wc");//program:wc(wordcount)22myargs[1]=strdup("p4.c");//arg:filetocount23myargs[2]=NULL;//markendofarray24execvp(myargs[0],myargs);//runswordcount25}else{26//parentgoesdownthispath(main)27intrc_wait=wait(NULL);28}29return0;30}Figure5.4:AllOfTheAboveWithRedirection(p4.c)5.5ProcessControlAndUsersBeyondfork(),exec(),andwait(),therearealotofotherinter-facesforinteractingwithprocessesinUNIXsystems.Forexample,thekill()systemcallisusedtosendsignalstoaprocess,includingdi-rectivestopause,die,andotherusefulimperatives.Forconvenience,inmostUNIXshells,certainkeystrokecombinationsareconguredtodeliveraspecicsignaltothecurrentlyrunningprocess;forexample,control-csendsaSIGINT(interrupt)totheprocess(normallyterminatingit)andcontrol-zsendsaSIGTSTP(stop)signalthuspausingtheprocessinmid-execution(youcanresumeitlaterwithacommand,e.g.,thefgbuilt-incommandfoundinmanyshells).Theentire

9 signalssubsystemprovidesarichinfrastruct
signalssubsystemprovidesarichinfrastructuretodeliverexternaleventstoprocesses,includingwaystoreceiveandprocessthosesignalswithinindividualprocesses,andwaystosendsignalstoindivid-ualprocessesaswellasentireprocessgroups.Tousethisformofcom-OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG INTERLUDE:PROCESSAPI9 ASIDE:RTFM—READTHEMANPAGESManytimesinthisbook,whenreferringtoaparticularsystemcallorlibrarycall,we'lltellyoutoreadthemanualpages,ormanpagesforshort.ManpagesaretheoriginalformofdocumentationthatexistonUNIXsystems;realizethattheywerecreatedbeforethethingcalledthewebexisted.Spendingsometimereadingmanpagesisakeystepinthegrowthofasystemsprogrammer;therearetonsofusefultidbitshiddeninthosepages.Someparticularlyusefulpagestoreadarethemanpagesforwhichevershellyouareusing(e.g.,tcsh,orbash),andcertainlyforanysystemcallsyourprogrammakes(inordertoseewhatreturnvaluesanderrorconditionsexist).Finally,readingthemanpagescansaveyousomeembarrassment.Whenyouaskcolleaguesaboutsomeintricacyoffork(),theymaysimplyreply:“RTFM.”Thisisyourcolleagues'wayofgentlyurgingyoutoReadTheManpages.TheFinRTFMjustaddsalittlecolortothephrase...munication,aprocessshouldusethesignal()systemcallto“catch”varioussignals;doingsoensuresthatwhenaparticularsignalisdeliv-eredtoaprocess,itwillsuspenditsnormalexecutionandrunaparticu-larpieceofcodeinresponsetothesignal.Readelsewhere[SR05]tolearnmoreaboutsignalsandtheirmanyintricacies.Thisnaturallyraisesthequestion:whocansendasignaltoaprocess,andwhocannot?Generally,thesystemsweusecanhavemultiplepeopleusingthematthesametime;ifoneofthesepeoplecanarbitrarilysendsignalssuchasSIGINT(tointerruptaprocess,likelyterminatingit),theusabilityandsecurityofthesystemwillbecompromised.Asaresult,modernsystemsincludeastrongconceptionofthenotiono

10 fauser.Theuser,afterenteringapasswordtoe
fauser.Theuser,afterenteringapasswordtoestablishcredentials,logsintogainaccesstosystemresources.Theusermaythenlaunchoneormanypro-cesses,andexercisefullcontroloverthem(pausethem,killthem,etc.).Usersgenerallycanonlycontroltheirownprocesses;itisthejoboftheoperatingsystemtoparceloutresources(suchasCPU,memory,anddisk)toeachuser(andtheirprocesses)tomeetoverallsystemgoals.5.6UsefulToolsTherearemanycommand-linetoolsthatareusefulaswell.Forexam-ple,usingthepscommandallowsyoutoseewhichprocessesarerun-ning;readthemanpagesforsomeusefulagstopasstops.Thetooltopisalsoquitehelpful,asitdisplaystheprocessesofthesystemandhowmuchCPUandotherresourcestheyareeatingup.Humorously,manytimeswhenyourunit,topclaimsitisthetopresourcehog;perhapsitisabitofanegomaniac.Thecommandkillcanbeusedtosendarbitraryc\r2008–20,ARPACI-DUSSEAUTHREEEASYPIECES 10INTERLUDE:PROCESSAPI ASIDE:THEUPERUSER(ROOT)Asystemgenerallyneedsauserwhocanadministerthesystem,andisnotlimitedinthewaymostusersare.Suchausershouldbeabletokillanarbitraryprocess(e.g.,ifitisabusingthesysteminsomeway),eventhoughthatprocesswasnotstartedbythisuser.Suchausershouldalsobeabletorunpowerfulcommandssuchasshutdown(which,unsurpris-ingly,shutsdownthesystem).InUNIX-basedsystems,thesespecialabil-itiesaregiventothesuperuser(sometimescalledroot).Whilemostuserscan'tkillotherusersprocesses,thesuperusercan.BeingrootismuchlikebeingSpider-Man:withgreatpowercomesgreatresponsibility[QI15].Thus,toincreasesecurity(andavoidcostlymistakes),it'susuallybettertobearegularuser;ifyoudoneedtoberoot,treadcarefully,asallofthedestructivepowersofthecomputingworldarenowatyourngertips.signalstoprocesses,ascantheslightlymoreuserfriendlykillall.Besuretousethesecarefully;ifyouaccidentallykillyourwindowmanager,thecomputeryouaresitti

11 nginfrontofmaybecomequitedifculttouse.F
nginfrontofmaybecomequitedifculttouse.Finally,therearemanydifferentkindsofCPUmetersyoucanusetogetaquickglanceunderstandingoftheloadonyoursystem;forexample,wealwayskeepMenuMeters(fromRagingMenacesoftware)runningonourMacintoshtoolbars,sowecanseehowmuchCPUisbeingutilizedatanymomentintime.Ingeneral,themoreinformationaboutwhatisgoingon,thebetter.5.7SummaryWehaveintroducedsomeoftheAPIsdealingwithUNIXprocesscre-ation:fork(),exec(),andwait().However,wehavejustskimmedthesurface.Formoredetail,readStevensandRago[SR05],ofcourse,particularlythechaptersonProcessControl,ProcessRelationships,andSignals;thereismuchtoextractfromthewisdomtherein.WhileourpassionfortheUNIXprocessAPIremainsstrong,weshouldalsonotethatsuchpositivityisnotuniform.Forexample,arecentpa-perbysystemsresearchersfromMicrosoft,BostonUniversity,andETHinSwitzerlanddetailssomeproblemswithfork(),andadvocatesforother,simplerprocesscreationAPIssuchasspawn()[B+19].Readit,andtherelatedworkitrefersto,tounderstandthisdifferentvantagepoint.Whileit'sgenerallygoodtotrustthisbook,remembertoothattheauthorshaveopinions;thoseopinionsmaynot(always)beaswidelysharedasyoumightthink.OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG INTERLUDE:PROCESSAPI11 ASIDE:KEYPROCESSAPITERMSEachprocesshasaname;inmostsystems,thatnameisanumberknownasaprocessID(PID).Thefork()systemcallisusedinUNIXsystemstocreateanewpro-cess.Thecreatoriscalledtheparent;thenewlycreatedprocessiscalledthechild.Assometimesoccursinreallife[J16],thechildprocessisanearlyidenticalcopyoftheparent.Thewait()systemcallallowsaparenttowaitforitschildtocom-pleteexecution.Theexec()familyofsystemcallsallowsachildtobreakfreefromitssimilaritytoitsparentandexecuteanentirelynewprogram.AUNIXshellcommonlyusesfork(),wait(),andexec()tolaunchusercom

12 mands;theseparationofforkandexecenablesf
mands;theseparationofforkandexecenablesfea-tureslikeinput/outputredirection,pipes,andothercoolfeatures,allwithoutchanginganythingabouttheprogramsbeingrun.Processcontrolisavailableintheformofsignals,whichcancausejobstostop,continue,oreventerminate.Whichprocessescanbecontrolledbyaparticularpersonisencap-sulatedinthenotionofauser;theoperatingsystemallowsmultipleusersontothesystem,andensuresuserscanonlycontroltheirownprocesses.Asuperusercancontrolallprocesses(andindeeddomanyotherthings);thisroleshouldbeassumedinfrequentlyandwithcautionforsecurityreasons.c\r2008–20,ARPACI-DUSSEAUTHREEEASYPIECES 12INTERLUDE:PROCESSAPI References[B+19]“Afork()intheroad”byAndrewBaumann,JonathanAppavoo,OrranKrieger,Tim-othyRoscoe.HotOS'19,Bertinoro,Italy.Afunpaperfulloffork()ingrage.ReadittogetanopposingviewpointontheUNIXprocessAPI.PresentedatthealwayslivelyHotOSworkshop,wheresystemsresearchersgotopresentextremeopinionsinthehopesofpushingthecommunityinnewdi-rections.[C63]“AMultiprocessorSystemDesign”byMelvinE.Conway.AFIPS'63FallJointComputerConference,NewYork,USA1963.Anearlypaperonhowtodesignmultiprocessingsystems;maybetherstplacethetermfork()wasusedinthediscussionofspawningnewprocesses.[DV66]“ProgrammingSemanticsforMultiprogrammedComputations”byJackB.DennisandEarlC.VanHorn.CommunicationsoftheACM,Volume9,Number3,March1966.Aclassicpaperthatoutlinesthebasicsofmultiprogrammedcomputersystems.UndoubtedlyhadgreatinuenceonProjectMAC,Multics,andeventuallyUNIX.[J16]“Theycouldbetwins!”byPhoebeJackson-Edwards.TheDailyMail.March1,2016..Thishard-hittingpieceofjournalismshowsabunchofweirdlysimilarchild/parentphotosandisfranklykindofmesmerizing.Goahead,wastetwominutesofyourlifeandcheckitout.Butdon'tforgettocomebackhere!This,inamicrocosm,isthedangerofsur

13 ngtheweb.[L83]“HintsforComputerSystemsD
ngtheweb.[L83]“HintsforComputerSystemsDesign”byButlerLampson.ACMOperatingSystemsReview,Volume15:5,October1983.Lampson'sfamoushintsonhowtodesigncomputersystems.Youshouldreaditatsomepointinyourlife,andprobablyatmanypointsinyourlife.[QI15]“WithGreatPowerComesGreatResponsibility”byTheQuoteInvestigator.Available:https://quoteinvestigator.com/2015/07/23/great-power.Thequoteinvestigatorconcludesthattheearliestmentionofthisconceptis1793,inacollectionofdecreesmadeattheFrenchNationalConvention.Thespecicquote:“Ilsdoiventenvisagerqu'unegranderesponsabilitestlasuiteinsparabled'ungrandpouvoir”,whichroughlytranslatesto“Theymustconsiderthatgreatresponsibilityfollowsinseparablyfromgreatpower.”Onlyin1962didthefollowingwordsappearinSpider-Man:“...withgreatpowertheremustalsocome–greatresponsibility!”SoitlooksliketheFrenchRevolutiongetscreditforthisone,notStanLee.Sorry,Stan.[SR05]“AdvancedProgrammingintheUNIXEnvironment”byW.RichardStevens,StephenA.Rago.Addison-Wesley,2005.AllnuancesandsubtletiesofusingUNIXAPIsarefoundherein.Buythisbook!Readit!Andmostimportantly,liveit.OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG INTERLUDE:PROCESSAPI13 Homework(Simulation)Thissimulationhomeworkfocusesonfork.py,asimpleprocesscre-ationsimulatorthatshowshowprocessesarerelatedinasingle“famil-ial”tree.ReadtherelevantREADMEfordetailsabouthowtorunthesimulator.Questions1.Run./fork.py-s10andseewhichactionsaretaken.Canyoupredictwhattheprocesstreelookslikeateachstep?Usethe-cagtocheckyouranswers.Trysomedifferentrandomseeds(-s)oraddmoreactions(-a)togetthehangofit.2.Onecontrolthesimulatorgivesyouisthefork percentage,con-trolledbythe-fag.Thehigheritis,themorelikelythenextactionisafork;theloweritis,themorelikelytheactionisanexit.Runthesimulatorwithalargenumberofactions(e

14 .g.,-a100)andvarythefork percentagefrom0
.g.,-a100)andvarythefork percentagefrom0.1to0.9.Whatdoyouthinktheresultingnalprocesstreeswilllooklikeasthepercent-agechanges?Checkyouranswerwith-c.3.Now,switchtheoutputbyusingthe-tag(e.g.,run./fork.py-t).Givenasetofprocesstrees,canyoutellwhichactionsweretaken?4.Oneinterestingthingtonoteiswhathappenswhenachildexits;whathappenstoitschildrenintheprocesstree?Tostudythis,let'screateaspecicexample:./fork.py-Aa+b,b+c,c+d,c+e,c-.Thisexamplehasprocess'a'create'b',whichinturncreates'c',whichthencreates'd'and'e'.However,then,'c'exits.Whatdoyouthinktheprocesstreeshouldlikeaftertheexit?Whatifyouusethe-Rag?Learnmoreaboutwhathappenstoorphanedpro-cessesonyourowntoaddmorecontext.5.Onelastagtoexploreisthe-Fag,whichskipsintermediatestepsandonlyaskstollinthenalprocesstree.Run./fork.py-Fandseeifyoucanwritedownthenaltreebylookingattheseriesofactionsgenerated.Usedifferentrandomseedstotrythisafewtimes.6.Finally,useboth-tand-Ftogether.Thisshowsthenalprocesstree,butthenasksyoutollintheactionsthattookplace.Bylook-ingatthetree,canyoudeterminetheexactactionsthattookplace?Inwhichcasescanyoutell?Inwhichcan'tyoutell?Trysomedif-ferentrandomseedstodelveintothisquestion.c\r2008–20,ARPACI-DUSSEAUTHREEEASYPIECES 14INTERLUDE:PROCESSAPI ASIDE:CODINGHOMEWORKSCodinghomeworksaresmallexerciseswhereyouwritecodetorunonarealmachinetogetsomeexperiencewithsomebasicoperatingsystemAPIs.Afterall,youare(probably)acomputerscientist,andthereforeshouldliketocode,right?Ifyoudon't,thereisalwaysCStheory,butthat'sprettyhard.Ofcourse,totrulybecomeanexpert,youhavetospendmorethanalittletimehackingawayatthemachine;indeed,ndeveryexcuseyoucantowritesomecodeandseehowitworks.Spendthetime,andbecomethewisemasteryouknowyoucanbe.Homework(Code)Inthishomework,youaretogainsomefa

15 miliaritywiththeprocessmanagementAPIsabo
miliaritywiththeprocessmanagementAPIsaboutwhichyoujustread.Don'tworry–it'sevenmorefunthanitsounds!You'llingeneralbemuchbetteroffifyoundasmuchtimeasyoucantowritesomecode,sowhynotstartnow?Questions1.Writeaprogramthatcallsfork().Beforecallingfork(),havethemainprocessaccessavariable(e.g.,x)andsetitsvaluetosome-thing(e.g.,100).Whatvalueisthevariableinthechildprocess?Whathappenstothevariablewhenboththechildandparentchangethevalueofx?2.Writeaprogramthatopensale(withtheopen()systemcall)andthencallsfork()tocreateanewprocess.Canboththechildandparentaccesstheledescriptorreturnedbyopen()?Whathappenswhentheyarewritingtotheleconcurrently,i.e.,atthesametime?3.Writeanotherprogramusingfork().Thechildprocessshouldprint“hello”;theparentprocessshouldprint“goodbye”.Youshouldtrytoensurethatthechildprocessalwaysprintsrst;canyoudothiswithoutcallingwait()intheparent?4.Writeaprogramthatcallsfork()andthencallssomeformofexec()toruntheprogram/bin/ls.Seeifyoucantryallofthevariantsofexec(),including(onLinux)execl(),execle(),execlp(),execv(),execvp(),andexecvpe().Whydoyouthinktherearesomanyvariantsofthesamebasiccall?5.Nowwriteaprogramthatuseswait()towaitforthechildprocesstonishintheparent.Whatdoeswait()return?Whathappensifyouusewait()inthechild?OPERATINGYSTEMS[VERSION1.01]WWW.OSTEP.ORG INTERLUDE:PROCESSAPI15 6.Writeaslightmodicationofthepreviousprogram,thistimeus-ingwaitpid()insteadofwait().Whenwouldwaitpid()beuseful?7.Writeaprogramthatcreatesachildprocess,andtheninthechildclosesstandardoutput(STDOUT FILENO).Whathappensifthechildcallsprintf()toprintsomeoutputafterclosingthedescriptor?8.Writeaprogramthatcreatestwochildren,andconnectsthestan-dardoutputofonetothestandardinputoftheother,usingthepipe()systemcall.c\r2008–20,ARPACI-DUSSEAUTHREEEASYP

Related Contents


Next Show more