Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process,...

33
Processes 11/3/16

Transcript of Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process,...

Page 1: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Processes11/3/16

Page 2: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Recall:thekernel’sjob

Ensurethatallrunningprocesseshavereasonableaccesstosystemresources:

• CPU• Memory• IOdevices

Providealoneview abstraction:eachprocessshouldrunasifitweretheonlyoneonthesystem.

Page 3: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

ManagingCPUcycles:timesharing

• MultipleprocessesperCPU• Eachprocessmakesprogressovertime• IllusionofparallelprogressbyrapidlyswitchingCPU• Whenscheduled,aprocessrunsforafewmilliseconds(1ms=10-3 seconds) beforegettingpreempted.

P1 P2

P3

P1 P2 P3quantum

P1P2P3

time

Page 4: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

• Statetransitions• Dispatch:allocatetheCPUtoaprocess• Preempt:takeawayCPUfromprocess• Sleep:processgivesupCPUtowaitforevent• Wakeup:eventoccurred,makeprocessready

ProcessStatenewprocess

Exit

wakeup

sleep

Ready Blocked

ExitedRunning

(onCPU)

dispatch preempt

Page 5: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Whymightaprocessbeblocked(unabletomakeprogress/useCPU)?

A. It’swaitingforanotherprocesstodosomething.

B. It’swaitingformemorytofindandreturnavalue.

C. It’swaitingforanI/Odevicetodosomething.

D. Morethanoneoftheabove.(Whichones?)

E. Someotherreason(s).

Page 6: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

HowisTimesharingImplemented?

• Kerneltracksthestateofeachprocess:• Running:actuallymakingprogress,usingCPU• Ready:abletomakeprogress,butnotusingCPU• Blocked:notabletomakeprogress,can’tuseCPU

• Aprocessrunsuntilstopped:• Canstopitselfbymakingasystemcall(TRAP)• Canbestoppedbythekernel(interrupt)

• Kernelrunstoperformacontextswitch:• Savethestateofthecurrentprocess• Selectsanotherreadyprocessandloaditsstate

Page 7: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

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,…

Page 8: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

HowaContextSwitchOccurs

• Processmakessystemcall(TRAP)orisinterrupted• Thesearetheonlywaysofenteringthekernel

• Inhardware• Switchfromusertokernelmode:amplifiespower• Gotofixedkernellocation:interrupt/traphandler

• Insoftware(inthekernelcode)• Savecontextoflast-runningprocess• Selectnewprocessfromthosethatareready• Restorecontextofselectedprocess• OSreturnscontroltoaprocessfrominterrupt/trap

Page 9: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Whyshouldthekernel(noteachprocess)controlcontextswitching?

A. Itwouldcausetoomuchoverhead.

B. TheycouldrefusetogiveuptheCPU.

C. Theydon’thaveenoughinformationaboutotherprocesses.

D. Someotherreason(s).

Page 10: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Policyquestion:howshouldthekernelpickthenextprocesstorun?

Therearelotsofreasonableoptions:• Keeprunningthesameprocesswhenpossible.• maximizethroughput

• Runtheprocessthathasbeenreadylongest.• ensurefairness

• Prioritizesomeprocesses.• Shoulduser(s)setthepriorities?• Shouldprioritybedeterminedautomatically?

Page 11: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Linux’sPolicy(You’renotresponsibleforthis.)

• Special“realtime”processclasses(highpriority)

• Otherprocesses:• Keepred-blackBSTofprocess,organizedbyhowmuchCPUtimethey’vereceived.• Pickthereadywithprocessthathasrunfortheshortesttimethusfar.• Runit,updateit’sCPUusagetime,addtotree.

• Interactiveprocesses:Usuallyblocked,lowtotalruntime,highpriority.

Page 12: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Wheredoprocessescomefrom?

Thefork() systemcallcreatesanewprocess.

Onboot,thekernelspawnsthe“init”process.

Init callsfork() tocreatechildprocesses.

Thoseprocessescanalsocreatechildrenwithfork.

Page 13: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

fork()

• Systemcall(functionprovidedbyOSkernel).

• Createsaduplicateoftherequestingprocess.• Processiscloningitself:

• CPUcontext• Memory“addressspace”

OS

Stack

TextDataHeap

OS

Stack

TextDataHeap

OS

Stack

TextDataHeap

(Almost)identicalclones

Page 14: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

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!

Page 15: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Howmanyhello’swillbeprinted?

fork();

printf(“hello”);

if (fork()) {

printf(“hello”);

}

fork();

printf(“hello”);

A.6B.8C.12D.16E.18

Page 16: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Afterfork(),callexec()

• Familyoffunctions(execl,execlp,execv,…).

• Replacethecurrentprocesswithanewone.

• Loadsprogramfromdisk:• Oldprocessisoverwritteninmemory.• Doesnotreturnunlesserror.

Page 17: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

• A“shell”istheprogramcontrollingyourterminal(e.g.,bash).

• Itcallsfork() tocreatenewprocesses,butwedon’twantaclone(anothershell).

• Wewantthechildtoexecutesomeotherprogram:callexec().

Page 18: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

1. fork()childprocess.

2. exec()desiredprogramtoreplacechild’saddressspace.

2. wait()forchildprocesstoterminate.

3. repeat…

Theparentandchildeachdosomethingdifferentnext.

Page 19: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

1. fork()childprocess.

Shell

fork()

Shell(p)

Shell(c)

Page 20: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

2. parent:wait()forchildtofinish

Shell

fork()

Shell(p)

Shell(c)

wait()

Page 21: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

2. child:exec()user-requestedprogram

Shell

fork()

Shell(p)

Shell(c)

wait() exec()

Page 22: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

2. child:exec()user-requestedprogram

Shell

fork()

Shell(p)

Shellnewprog

wait() exec()

Runstocompletion

Page 23: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

3. childprogramterminates,cyclerepeats

Shell

fork()

Shell(p)

Shellnewprog

wait() exec()

Runstocompletion

Childterminates

Page 24: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Commonfork()usage:Shell

3. childprogramterminates,cyclerepeats

Shell

fork()

Shell(p)

Shellnewprog

wait() exec()

Runstocompletion

ChildterminatesShell(p)

Parentprocess(shell)resumes

Page 25: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

ProcessTermination

Aprocessterminateswhen:• main returns• Itcallsexit()• Itreceivesaterminationsignal(fromtheOSoranotherprocess)

• Inallcases,itprocessproducesstatusinformation.• Theparentprocessreceivesthisinformation.

Page 26: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

WhatHappenswhenaprocessexits?Itbecomesazombieprocessuntilitsparentreapsit.

Zombieprocess:• exited,mostlydead,notrunnableanymore• waitingforparenttocompletelyremoveallofitsstatefromthesystem

26

Page 27: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Theparentprocessisresponsibleforcleaningupchildprocessstate.Twooptions:

1. Parentexplicitlywaitsforchildtoexitbycallingawaitfunction:• wait:waitforanychildtoexit(pid returned).• waitpid:waitforaspecificchildtoexit.

2. ParentreceivesaSIGCHILDsignal,andthesignalhandlercodecallswait toreapthechild.

27

Reapingzombies

Page 28: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Summary:systemcallsforprocesses• fork:spawnsnewprocess.• Calledonce,Returnstwice(inparentandchildprocess).

• exit:terminatesownprocess.• Calledonce,neverreturns.• Putsitinto“zombie”status.

• wait orwaitpid:reapterminatedchildren.• exec family:runsnewprograminexistingprocess.• Calledonce,(normally)neverreturns.

28

Page 29: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

SignalsSignal:asoftwareinterrupt:asmallmessagetotell

aprocessthatsomeeventhashappened.• OSsends asignaltoaprocess

• Onbehalfofanotherprocessthatcalledthekill syscall• Astheresultofsomeevent (NULLpointerdereference)

• Aprocessreceives asignalAsynchronous:signalee doesn’tknowwhenitwillgetoneAsignalispending beforeaprocessreceivesit

• Asignalinterrupts thereceivingprocess,whichthenrunssignalhandlercode• defaulthandlersforeachsignaltypeinOS• programmercanalsoaddsignalhandlercode

29

Page 30: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

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)

Page 31: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

ReceivingaSignal• Adestinationprocessreceives asignalwhenitisforcedbythekerneltoreactinsomewaytothedeliveryofthesignal.

• Threepossiblewaystoreact:• Ignore thesignal(donothing)notallsignalscanbeignored(e.g.SIGKILL)• Terminate theprocessonreceiptofsignal• Catch thesignalbyexecutingauser-levelfunctioncalledsignalhandler

31

Page 32: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

InstallingSignalHandlerssignal(int signum, handler_t *handler);

• Modifiesthedefaultactionassociatedwiththereceiptofaparticularsignal.

• handler isasignalhandlerfunction• Whenprogramreceivessignal,itjumpstostartexecutingthehandler function.• Whenthehandler doneexecuting,controlpassesbacktoinstructioninthecontrolflowoftheprocessthatwasinterruptedbyreceiptofthesignal.

32

Page 33: Processes - cs.swarthmore.edu€¦ · • Other processes: • Keep red-black BST of process, organized by how much CPU time they’ve received. • Pick the ready with process that

Summary

• ProcessesarecycledoffandonCPUrapidly.• Mechanism:contextswitch• Policy:CPUscheduling

• Processesarecreatedbyfork().

• Otherfunctionstomanageprocesses:• exec():replaceaddressspacewithnewprogram• exit():terminateprocess• wait():reapchildprocess,getstatusinfo

• Signalscommunicateeventstoprocesses.