processes - cs.swarthmore.edu€¦ · • other processes: • keep red-black bst of process,...
TRANSCRIPT
Processes11/3/16
Recall:thekernel’sjob
Ensurethatallrunningprocesseshavereasonableaccesstosystemresources:
• CPU• Memory• IOdevices
Providealoneview abstraction:eachprocessshouldrunasifitweretheonlyoneonthesystem.
ManagingCPUcycles:timesharing
• MultipleprocessesperCPU• Eachprocessmakesprogressovertime• IllusionofparallelprogressbyrapidlyswitchingCPU• Whenscheduled,aprocessrunsforafewmilliseconds(1ms=10-3 seconds) beforegettingpreempted.
P1 P2
P3
P1 P2 P3quantum
P1P2P3
time
• Statetransitions• Dispatch:allocatetheCPUtoaprocess• Preempt:takeawayCPUfromprocess• Sleep:processgivesupCPUtowaitforevent• Wakeup:eventoccurred,makeprocessready
ProcessStatenewprocess
Exit
wakeup
sleep
Ready Blocked
ExitedRunning
(onCPU)
dispatch preempt
Whymightaprocessbeblocked(unabletomakeprogress/useCPU)?
A. It’swaitingforanotherprocesstodosomething.
B. It’swaitingformemorytofindandreturnavalue.
C. It’swaitingforanI/Odevicetodosomething.
D. Morethanoneoftheabove.(Whichones?)
E. Someotherreason(s).
HowisTimesharingImplemented?
• Kerneltracksthestateofeachprocess:• Running:actuallymakingprogress,usingCPU• Ready:abletomakeprogress,butnotusingCPU• Blocked:notabletomakeprogress,can’tuseCPU
• Aprocessrunsuntilstopped:• Canstopitselfbymakingasystemcall(TRAP)• Canbestoppedbythekernel(interrupt)
• Kernelrunstoperformacontextswitch:• Savethestateofthecurrentprocess• Selectsanotherreadyprocessandloaditsstate
KernelMaintainsProcessTable
• Listofprocessesandtheirstates• Alsosometimescalled“processcontrolblock(PCB)”
• Otherstateinfoincludes• CPUcontext(registervalues)• areasofmemorybeingused• otherinformation
Process ID(PID) State Otherinfo1534 Ready Savedcontext,…
34 Running Memoryareasused,…
487 Ready Saved context,…
9 Blocked Conditiontounblock,…
HowaContextSwitchOccurs
• Processmakessystemcall(TRAP)orisinterrupted• Thesearetheonlywaysofenteringthekernel
• Inhardware• Switchfromusertokernelmode:amplifiespower• Gotofixedkernellocation:interrupt/traphandler
• Insoftware(inthekernelcode)• Savecontextoflast-runningprocess• Selectnewprocessfromthosethatareready• Restorecontextofselectedprocess• OSreturnscontroltoaprocessfrominterrupt/trap
Whyshouldthekernel(noteachprocess)controlcontextswitching?
A. Itwouldcausetoomuchoverhead.
B. TheycouldrefusetogiveuptheCPU.
C. Theydon’thaveenoughinformationaboutotherprocesses.
D. Someotherreason(s).
Policyquestion:howshouldthekernelpickthenextprocesstorun?
Therearelotsofreasonableoptions:• Keeprunningthesameprocesswhenpossible.• maximizethroughput
• Runtheprocessthathasbeenreadylongest.• ensurefairness
• Prioritizesomeprocesses.• Shoulduser(s)setthepriorities?• Shouldprioritybedeterminedautomatically?
Linux’sPolicy(You’renotresponsibleforthis.)
• Special“realtime”processclasses(highpriority)
• Otherprocesses:• Keepred-blackBSTofprocess,organizedbyhowmuchCPUtimethey’vereceived.• Pickthereadywithprocessthathasrunfortheshortesttimethusfar.• Runit,updateit’sCPUusagetime,addtotree.
• Interactiveprocesses:Usuallyblocked,lowtotalruntime,highpriority.
Wheredoprocessescomefrom?
Thefork() systemcallcreatesanewprocess.
Onboot,thekernelspawnsthe“init”process.
Init callsfork() tocreatechildprocesses.
Thoseprocessescanalsocreatechildrenwithfork.
fork()
• Systemcall(functionprovidedbyOSkernel).
• Createsaduplicateoftherequestingprocess.• Processiscloningitself:
• CPUcontext• Memory“addressspace”
OS
Stack
TextDataHeap
OS
Stack
TextDataHeap
OS
Stack
TextDataHeap
(Almost)identicalclones
fork() returnvalue• Thetwoprocessesareidenticalineveryway,exceptforthereturnvalueoffork().• Thechildgetsareturnvalueof0.• Theparentgetsareturnvalueofchild’sPID.
pid_t pid = fork(); // both continue after callif (pid == 0) {
printf("hello from child\n");} else {
printf("hello from parent\n");}
Whichprocessexecutesnext?Child?Parent?Someotherprocess?
UptoOStodecide.Noguarantees.Don’trelyonparticularbehavior!
Howmanyhello’swillbeprinted?
fork();
printf(“hello”);
if (fork()) {
printf(“hello”);
}
fork();
printf(“hello”);
A.6B.8C.12D.16E.18
Afterfork(),callexec()
• Familyoffunctions(execl,execlp,execv,…).
• Replacethecurrentprocesswithanewone.
• Loadsprogramfromdisk:• Oldprocessisoverwritteninmemory.• Doesnotreturnunlesserror.
Commonfork()usage:Shell
• A“shell”istheprogramcontrollingyourterminal(e.g.,bash).
• Itcallsfork() tocreatenewprocesses,butwedon’twantaclone(anothershell).
• Wewantthechildtoexecutesomeotherprogram:callexec().
Commonfork()usage:Shell
1. fork()childprocess.
2. exec()desiredprogramtoreplacechild’saddressspace.
2. wait()forchildprocesstoterminate.
3. repeat…
Theparentandchildeachdosomethingdifferentnext.
Commonfork()usage:Shell
1. fork()childprocess.
Shell
fork()
Shell(p)
Shell(c)
Commonfork()usage:Shell
2. parent:wait()forchildtofinish
Shell
fork()
Shell(p)
Shell(c)
wait()
Commonfork()usage:Shell
2. child:exec()user-requestedprogram
Shell
fork()
Shell(p)
Shell(c)
wait() exec()
Commonfork()usage:Shell
2. child:exec()user-requestedprogram
Shell
fork()
Shell(p)
Shellnewprog
wait() exec()
Runstocompletion
Commonfork()usage:Shell
3. childprogramterminates,cyclerepeats
Shell
fork()
Shell(p)
Shellnewprog
wait() exec()
Runstocompletion
Childterminates
Commonfork()usage:Shell
3. childprogramterminates,cyclerepeats
Shell
fork()
Shell(p)
Shellnewprog
wait() exec()
Runstocompletion
ChildterminatesShell(p)
Parentprocess(shell)resumes
ProcessTermination
Aprocessterminateswhen:• main returns• Itcallsexit()• Itreceivesaterminationsignal(fromtheOSoranotherprocess)
• Inallcases,itprocessproducesstatusinformation.• Theparentprocessreceivesthisinformation.
WhatHappenswhenaprocessexits?Itbecomesazombieprocessuntilitsparentreapsit.
Zombieprocess:• exited,mostlydead,notrunnableanymore• waitingforparenttocompletelyremoveallofitsstatefromthesystem
26
Theparentprocessisresponsibleforcleaningupchildprocessstate.Twooptions:
1. Parentexplicitlywaitsforchildtoexitbycallingawaitfunction:• wait:waitforanychildtoexit(pid returned).• waitpid:waitforaspecificchildtoexit.
2. ParentreceivesaSIGCHILDsignal,andthesignalhandlercodecallswait toreapthechild.
27
Reapingzombies
Summary:systemcallsforprocesses• fork:spawnsnewprocess.• Calledonce,Returnstwice(inparentandchildprocess).
• exit:terminatesownprocess.• Calledonce,neverreturns.• Putsitinto“zombie”status.
• wait orwaitpid:reapterminatedchildren.• exec family:runsnewprograminexistingprocess.• Calledonce,(normally)neverreturns.
28
SignalsSignal:asoftwareinterrupt:asmallmessagetotell
aprocessthatsomeeventhashappened.• OSsends asignaltoaprocess
• Onbehalfofanotherprocessthatcalledthekill syscall• Astheresultofsomeevent (NULLpointerdereference)
• Aprocessreceives asignalAsynchronous:signalee doesn’tknowwhenitwillgetoneAsignalispending beforeaprocessreceivesit
• Asignalinterrupts thereceivingprocess,whichthenrunssignalhandlercode• defaulthandlersforeachsignaltypeinOS• programmercanalsoaddsignalhandlercode
29
SignalsOSidentifiesspecificsignalbyitsnumber,examples:
30
ID Name DefaultAction CorrespondingEvent2 SIGINT Terminate Interrupt(e.g.,ctl-cfromkeyboard)9 SIGKILL Terminate Killprogram(cannotoverrideorignore)
11 SIGSEGV Terminate Invalidmemoryreference(e.g.NULLptr)14 SIGALRM Terminate Timersignal17 SIGCHLD Ignore Childstoppedorterminated
SendingSignals:Unixcommand:$ kill -9 1234 #sendSIGKILL signaltoprocess1234Systemcall:kill(1234, SIGKILL); //sendSIGKILL toprocess1234
Implicitlysent: side-effectofprogramdoingsomething(NULLptr dereferencecausesSIGSEGV)
ReceivingaSignal• Adestinationprocessreceives asignalwhenitisforcedbythekerneltoreactinsomewaytothedeliveryofthesignal.
• Threepossiblewaystoreact:• Ignore thesignal(donothing)notallsignalscanbeignored(e.g.SIGKILL)• Terminate theprocessonreceiptofsignal• Catch thesignalbyexecutingauser-levelfunctioncalledsignalhandler
31
InstallingSignalHandlerssignal(int signum, handler_t *handler);
• Modifiesthedefaultactionassociatedwiththereceiptofaparticularsignal.
• handler isasignalhandlerfunction• Whenprogramreceivessignal,itjumpstostartexecutingthehandler function.• Whenthehandler doneexecuting,controlpassesbacktoinstructioninthecontrolflowoftheprocessthatwasinterruptedbyreceiptofthesignal.
32
Summary
• ProcessesarecycledoffandonCPUrapidly.• Mechanism:contextswitch• Policy:CPUscheduling
• Processesarecreatedbyfork().
• Otherfunctionstomanageprocesses:• exec():replaceaddressspacewithnewprogram• exit():terminateprocess• wait():reapchildprocess,getstatusinfo
• Signalscommunicateeventstoprocesses.