Briefnotesonmemoryoperatinsinfork(),exec()andvfork()byDr.Beck Background:Theaddressspaceofaprocessismadeupofanumberofsegments,eachof whichisacontiguousareaofmemoryusedforaparticularpurpose.Inthisdiscussion,we considerprocessedwiththesesegments:code,staticdata,heapandstack. Fork():Thefork()callcreatesanewprocess(thechild)byallocatinganunusedtask controlblock(TCB)andcopyingmanyofthefieldsfromthecallingprocess’(theparent’s) TCB.Thus,whilethechildisnotidenticaltotheparentinallrespects,theysharemany attributesincommon.Forexample,theyhavethesameuserID(uid)butdifferentprocess IDs(pid). Fork()isabletoshareread-onlysegmentsbetweentheparentandchild,allowingthe child’saddressspacetobecreatedusingthesamememoryastheparent.Inourexample, theonlyready-onlysegmentisthecodesegment.Sinceneitherparentnorchildcanmodify thissegment,theycanuseitsimultaneouslywithnopossibilityofinterfering. Theothersegmentsinourexample(staticdata,heapandstack)areallwritable,andso sharingthembetweenaparentandchildexecutingsimultaneouslycouldresultin interferencebetweenthosetwoprocesses(raceconditions).Thus,theforksystemcall allocatesnewmemoryforthosesegmentsinthechild(thesamesizeasthesegmentsinthe parent)andcopiesthecontentsofeachsegmentfromtheparenttothecorresponding segmentinthechild.Theparentandchildtheneachhaveaprivatecopyofthecontentsof eachofthesesegmentsstoredinitsownprivatememory,andsoparentandchildcanboth executesimultaneouslywithoutthepossibilityofinterference. Exec(): Exec()isasystemcallthatreplacestheaddressspaceofarunningprocess withthecontentsofanexecutablefile.Thecodeandstaticdatasegmentsarereadfromthe fileintonewlyallocatedmemory,thestackandheapareinitializedtobeempty. Itisverycommonforacommandlineinterpreter(shell)orGUItoinvokeanexecutablefile (commandoruserprogram)bycallfork()tocreateanewchildprocess,andthechild processthenalmostimmediatelycallingexec()tostarttheprogramstoredinthefile.In thisscenarioalltheworkthatdoesintocopyingtheaddressspaceofthechild(creatingthe staticdata,heapandstacksegments)isalmostimmediatelyundonebythecalltoexec(). Vfork(): Vfork()isameansforaparenttoavoidtheoverheadofcopyingtheparent’s addressspacewhenacalltoexec()willbemadealmostimmediatelyafterprocess creation.Thecalltovfork()issimilartofork()butitdoesnotallocatenewmemoryfor thewritablesegments,insteadallowingthechildtoexecuteusingthememorysegmentsof theparent.Inordertoavoidinterferencebetweenparentandchild,theparentisnot allowedtoexecuteafterthecalltovfork()untilthechildmakesacalltoexec(). Vfork()avoidstheneedtoallocateandcopymemoryforthechild’saddressspace,but becausethechilddoessharetheparent’saddressspaceitmustbeverycarefulaboutwhat variablesitmodifiesbeforecallingexec().Ifitchangesanythingthatwillcauseproblems intheparentonceitstartsrunningagain,theparentmightexperienceerrors.Thuswecan saythatvfork()isnotcompletelysafe(becauseitcancauseproblemsifthechildmakes error-causingmodifications)butitcanbemuchmoreefficientthanfork().