Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
CarnegieMellon
1
Excep&onalControlFlow
15-213:Introduc7ontoComputerSystemsRecita7on9:Monday,October26th,2015CelesteNearyAdaptedfromslidesbyIanHartwig
CarnegieMellon
2
Agenda¢ MidtermWrap-Up¢ Excep7onalControlFlow¢ Processes¢ Signals¢ Shelllab
CarnegieMellon
3
MidtermWrap-Up¢ MidtermsscoresareonAutolab¢ ViewexamsduringOHin5207¢ Regraderequests–inwri7ng(hardcopyonly)
CarnegieMellon
4
Excep&onalControlFlow¢ Uptonow:twomechanismsforchangingcontrolflow:
§ Jumpsandbranches§ CallandreturnBothreacttochangesinprogramstate
¢ Insufficientforausefulsystem:Difficulttoreacttochangesinsystemstate§ dataarrivesfromadiskoranetworkadapter§ instruc7ondividesbyzero§ userhitsCtrl-Catthekeyboard§ System7merexpires
¢ Systemneedsmechanismsfor“excep7onalcontrolflow”
CarnegieMellon
5
AsynchronousExcep&ons(Interrupts)¢ Causedbyeventsexternaltotheprocessor
§ Indicatedbyse`ngtheprocessor’sinterruptpin§ Handlerreturnsto“next”instruc7on
¢ Examples:§ I/Ointerrupts
§ hi`ngCtrl-Catthekeyboard§ arrivalofapacketfromanetwork§ arrivalofdatafromadisk
§ Hardresetinterrupt§ hi`ngtheresetbucon
§ Sodresetinterrupt§ hi`ngCtrl-Alt-DeleteonaPC
CarnegieMellon
6
SynchronousExcep&ons¢ Causedbyeventsthatoccurasaresultofexecu7ngan
instruc7on:§ Traps
§ Inten7onal§ Examples:systemcalls,breakpointtraps,specialinstruc7ons§ Returnscontrolto“next”instruc7on
§ Faults§ Uninten7onalbutpossiblyrecoverable§ Examples:pagefaults(recoverable),protec7onfaults(unrecoverable),floa7ngpointexcep7ons
§ Eitherre-executesfaul7ng(“current”)instruc7onoraborts§ Aborts
§ uninten7onalandunrecoverable§ Examples:parityerror,machinecheck§ Abortscurrentprogram
CarnegieMellon
7
Processes¢ Whatisaprogram?
§ Abunchofdataandinstruc7onsstoredinanexecutablebinaryfile§ Wricenaccordingtoaspecifica7onthattellsuserswhatitis
supposedtodo§ Statelesssincebinaryfileissta7c
CarnegieMellon
8
Processes¢ Defini7on:Aprocessisaninstanceofarunningprogram.¢ Processprovideseachprogramwithtwokeyabstrac7ons:
§ Logicalcontrolflow§ EachprogramseemstohaveexclusiveuseoftheCPU
§ Privatevirtualaddressspace§ Eachprogramseemstohaveexclusiveuseofmainmemory§ Givestherunningprogramastate
¢ HowaretheseIllusionsmaintained?§ Processexecu7onsinterleaved(mul7tasking)orrunonseparate
cores§ Addressspacesmanagedbyvirtualmemorysystem
§ Justknowthatthisexistsfornow;we’lltalkaboutitsoon
CarnegieMellon
9
Processes¢ FourbasicStates
§ Running§ Execu7nginstruc7onsontheCPU§ NumberboundedbynumberofCPUcores
§ Runnable§ Wai7ngtoberunning
§ Blocked§ Wai7ngforanevent,maybeinputfromSTDIN§ Notrunnable
§ Zombie§ Terminated,notyetreaped
CarnegieMellon
10
Processes¢ Fourbasicprocesscontrolfunc7onfamilies:
§ fork()§ exec()
§ Andothervariantssuchasexecve()§ exit()§ wait()
§ Andvariantslikewaitpid()
¢ StandardonallUNIX-basedsystems¢ Don’tbeconfused:
Fork(),Exit(),Wait()areallwrappersprovidedbyCS:APP
CarnegieMellon
11
Processes¢ intfork(void)
§ createsanewprocess(childprocess)thatisiden7caltothecallingprocess(parentprocess)
§ OScreatesanexactduplicateofparent’sstate:§ Virtualaddressspace(memory),includingheapandstack§ Registers,exceptforthereturnvalue(%eax/%rax)§ Filedescriptorsbutfilesareshared
§ ResultàEqualbutseparatestate
§ Forkisinteres7ng(andodenconfusing)becauseitiscalledoncebutreturnstwice
CarnegieMellon
12
Processes¢ intfork(void)
§ returns0tothechildprocess§ returnschild’spid(processid)totheparentprocess§ Usuallyusedlike:pid_tpid=fork();if(pid==0){//pidis0sowecandetectchildprintf("hellofromchild\n");}else{//pid=child’sassignedpidprintf("hellofromparent\n");}
CarnegieMellon
13
Processes¢ intexec()
§ Replacesthecurrentprocess’sstateandcontext§ ButkeepsPID,openfiles,andsignalcontext
§ Providesawaytoloadandrunanotherprogram§ Replacesthecurrentrunningmemoryimagewiththatofnewprogram
§ Setupstackwithargumentsandenvironmentvariables§ Startexecu7onattheentrypoint
§ Neverreturnsonsuccessfulexecu7on§ Thenewlyloadedprogram’sperspec7ve:asiftheprevious
programhasnotbeenrunbefore§ Moreusefulvariantisintexecve()§ Moreinforma7on?man3exec
CarnegieMellon
14
Processes¢ voidexit(intstatus)
§ Normallyreturnwithstatus0(othernumbersindicateanerror)§ Terminatesthecurrentprocess§ OSfreesresourcessuchasheapmemoryandopenfiledescriptors
andsoon…§ Reducetoazombiestate
§ Mustwaittobereapedbytheparentprocess(ortheinitprocessiftheparentdied)
§ Signalissenttotheparentprocessno7fyingofdeath§ Reapercaninspecttheexitstatus
CarnegieMellon
15
Processes¢ intwait(int*child_status)
§ suspendscurrentprocessun7loneofitschildrenterminates§ returnvalueisthepidofthechildprocessthatterminated
§ Whenwaitreturnsapid>0,childprocesshasbeenreaped§ Allchildresourcesfreed
§ ifchild_status!=NULL,thentheobjectitpointstowillbesettoastatusindica7ngwhythechildprocessterminated
§ Moreusefulvariantisintwaitpid()§ Fordetails:man2wait
CarnegieMellon
16
ProcessExamples¢ Whatarethepossible
output(assumingforksucceeds)?§ Child!
Parent!§ Parent!
Child!
¢ Howtogetthechildtoalwaysprintfirst?
pid_tchild_pid=fork();if(child_pid==0){/*onlychildcomeshere*/printf(“Child!\n”);exit(0);}else{printf(“Parent!\n”);}
CarnegieMellon
17
intstatus;pid_tchild_pid=fork();if(child_pid==0){/*onlychildcomeshere*/printf(“Child!\n”);exit(0);}else{waitpid(child_pid,&status,0);printf(“Parent!\n”);}
ProcessExamples¢ Waits7lthechildhas
terminated.Parentcaninspectexitstatusofchildusing‘status’§ WEXITSTATUS(status)
¢ Outputalways:Child!Parent!
CarnegieMellon
18
ProcessExamples
¢ Anexampleofsomethinguseful.
¢ Whyisthefirstarg“/bin/ls”?¢ Willchildreachhere?
intstatus;pid_tchild_pid=fork();char*argv[]={“/bin/ls”,“-l”,NULL};char*env[]={…,NULL};if(child_pid==0){/*onlychildcomeshere*/execve(“/bin/ls”,argv,env);/*willchildreachhere?*/}else{waitpid(child_pid,&status,0);…parentcontinueexecution…}
CarnegieMellon
19
ProcessExamples¢ UnixProcessHierarchy:
Login shell
Child Child Child
Grandchild Grandchild
[0]
Daemon e.g. httpd
init [1]
CarnegieMellon
20
Signals¢ Asignalisasmallmessagethatno7fiesaprocessthatanevent
ofsometypehasoccurredinthesystem§ akintoexcep7onsandinterrupts(asynchronous)§ sentfromthekernel(some7mesattherequestofanotherprocess)toa
process§ signaltypeisiden7fiedbysmallintegerID’s(1-30)§ onlyinforma7oninasignalisitsIDandthefactthatitarrived
ID Name Default Action Corresponding Event2 SIGINT Terminate Interrupt (e.g., ctl-c from keyboard)9 SIGKILL Terminate Kill program (cannot override or ignore)
11 SIGSEGV Terminate & Dump Segmentation violation14 SIGALRM Terminate Timer signal17 SIGCHLD Ignore Child stopped or terminated
CarnegieMellon
21
Signals¢ Kernelsends(delivers)asignaltoades2na2onprocessby
upda7ngsomestateinthecontextofthedes7na7onprocess
¢ Kernelsendsasignalforoneofthefollowingreasons:§ KernelhasdetectedasystemeventsuchasCtrl-C(SIGINT),divide-
by-zero(SIGFPE),orthetermina7onofachildprocess(SIGCHLD)§ Anotherprogramcalledthekill()func7on§ Theuserusedakillu7lity
CarnegieMellon
22
Signals¢ Ades7na7onprocessreceivesasignalwhenitisforcedby
thekerneltoreactinsomewaytothedeliveryofthesignal
¢ Receivingasignalisnon-queuing§ Thereisonlyonebitinthecontextpersignal§ Receiving1or300SIGINTslooksthesametotheprocess
¢ Signalsarereceivedatacontextswitch¢ Threepossiblewaystoreact:
§ Ignorethesignal(donothing)§ Terminatetheprocess(withop7onalcoredump)§ Catchthesignalbyexecu7ngauser-levelfunc7oncalledsignal
handler§ Akintoahardwareexcep7onhandlerbeingcalledinresponsetoanasynchronousinterrupt
CarnegieMellon
23
Signals¢ Ades7na7onprocessreceivesasignalwhenitisforcedby
thekerneltoreactinsomewaytothedeliveryofthesignal
¢ Blockingsignals§ Some7mescodeneedstorunthroughasec7onthatcan’tbe
interrupted§ Implementedwithsigprocmask()
¢ Wai7ngforsignals§ Some7mes,wewanttopauseexecu7onun7lwegetaspecific
signal§ Implementedwithsigsuspend()
¢ Can’tmodifybehaviorofSIGKILLandSIGSTOP
CarnegieMellon
24
Signals¢ Signalhandlers
§ Canbeinstalledtorunwhenasignalisreceived§ Theformisvoidhandler(intsignum){…}§ Separateflowofcontrolinthesameprocess§ Resumesnormalflowofcontroluponreturning§ Canbecalledany&mewhentheappropriatesignalisfired
CarnegieMellon
25
Signals¢ intsigsuspend(constsigset_t*mask)
§ Can’tusewait()twice–usesigsuspend!§ Temporarilyreplacesthesignalmaskofthecallingprocesswiththe
maskgiven§ Suspendstheprocessun7ldeliveryofasignalwhoseac7onisto
invokeasignalhandlerorterminateaprocess§ Returnsifthesignaliscaught
§ Signalmaskrestoredtothepreviousstate§ Usesigaddset(),sigemptyset(),etc.tocreatethemask
CarnegieMellon
26
SignalExamples¢ Everyprocessbelongstoexactlyoneprocessgroup¢ Processgroupscanbeusedtodistributesignalseasily¢ Aforkedprocessbecomesamemberoftheparent’s
processgroup
Fore-groundjob
Back-groundjob#1
Back-groundjob#2
Shell
Child Child
pid=10 pgid=10
Foregroundprocessgroup20
Backgroundprocessgroup32
Backgroundprocessgroup40
pid=20 pgid=20
pid=32 pgid=32
pid=40 pgid=40
pid=21 pgid=20
pid=22 pgid=20
getpgrp()Returnprocessgroupofcurrentprocess
setpgid() Changeprocessgroupofaprocess
CarnegieMellon
27
//sigchldhandlerinstalledpid_tchild_pid=fork();if(child_pid==0){/*childcomeshere*/execve(……);}else{add_job(child_pid);}
SignalExamples
¢ Doesadd_joborremove_job()comefirst?¢ Wherecanweblocksignalsinthiscodetoguarantee
correctexecu7on?
voidsigchld_handler(intsignum){intstatus;pid_tchild_pid=waitpid(-1,&status,WNOHANG);if(WIFEXITED(status))remove_job(child_pid);}
CarnegieMellon
28
//sigchldhandlerinstalledpid_tchild_pid=fork();if(child_pid==0){/*childcomeshere*/execve(……);}else{add_job(child_pid);}
SignalExamples
¢ Doesadd_joborremove_job()comefirst?¢ Wherecanweblocksignalsinthiscodetoguarantee
correctexecu7on?
voidsigchld_handler(intsignum){intstatus;pid_tchild_pid=waitpid(-1,&status,WNOHANG);if(WIFEXITED(status))remove_job(child_pid);}
BlockSIGCHLD
UnblockSIGCHLD
UnblockSIGCHLD
CarnegieMellon
29
ShellLab¢ ShellLabisout!¢ DueTuesday,November3rdat11:59pm¢ Readthecodewe’vegivenyou
§ There’salotofstuffyoudon’tneedtowriteyourself;wegaveyouquiteafewhelperfunc7ons
§ It’sagoodexampleofthecodeweexpectfromyou!
¢ Don’tbeafraidtowriteyourownhelperfunc7ons;thisisnotasimpleassignment
CarnegieMellon
30
ShellLab¢ Readmanpages.Youmayfindthefollowingfunc7ons
helpful:§ sigemptyset()§ sigaddset()§ sigprocmask()§ sigsuspend()§ waitpid()§ open()§ dup2()§ setpgid()§ kill()
¢ Pleasedonotusesleep()tosolvesynchroniza7onissues.
CarnegieMellon
31
ShellLab¢ Hazards
§ Racecondi7ons§ Hardtodebugsostartearly(andthinkcarefully)
§ Reapingzombies§ Racecondi7ons§ Handlingsignalscorrectly
§ Wai7ngforforegroundjob§ Thinkcarefullyaboutwhattherightwaytodothisis
CarnegieMellon
32
ShellLabTes&ng¢ Runyourshell
§ Thisisthefunpart!¢ tshref
§ Howshouldtheshellbehave?¢ runtrace
§ Eachtracetestsonefeature.