Announcements
• PeerWiseaccountsarenowlive.– FirstPeerWiseques9ons/reviewsduetomorrow(Thursday)at11:59pm
• Homework1isonline(dueonMonday7/6)
• Project1isonline(duenextFriday7/10)– PleaseemailmeprojectgroupsASAP.
– Milestonetes9ngonMondayatMidnight.
Review
• Opera9ngSystemsprovide:– Resourcemanagement
– Abstrac9onsforapplica9ondevelopment
• Protec9on– UsermodevsKernelmode
• HardwareSupport– Interrupts&Excep9ons
GoalsforToday
• Whatisconcurrencyandwhendowewantit?
• Whatarethebasicunitsofexecu9oninanOS?• HowaretheseunitsstoredandmanagedinanOS?• Whatarethepossiblestatesofthese?
• Howdotheytransi9onfromstatetostate?• Howaretheycreatedanddestroyed?• Mechanismsforinter‐processcommunica9on
Concurrency
• Uniprogramming– OSrunsasinglejobun9litiscompleted.
• Mul9programming– OShasaqueueofjobs– Selectsonejobtorun– IfthejobhastowaitforI/Oorhasrunforawhile,theOSsavesitsstateandputsitbackintothequeue.
– Repeatlast2stepsun9lalljobscomplete.
Whichtouse?
• Whendoesitmakesensetouseauniprogrammingmodel?– Don’twantperformanceoverheadofswitchingjobs– Don’tneed/wantaddi9onalOScomplexity.
• Whendoesitmakesensetouseamul9programmingmodel?– Wanttoseeprogressonmanyjobsatthesame9me.
– Beeeru9lizeresourceswhenjobswaitforI/O
Concurrency(cont)
• Uniprogramming:onejob/taskata9me– Batchschedulers,suchasinmanysupercompu9ngclusters,jobsrun
sequen9allytocomple9on;MS/DOS,executeonecommandata9me
• Mul9programming:manyjobs/tasksata9me– Time‐sharing,wherejobscoexistandresourcesare9me‐sliced
– Usedinpersonalcomputersandsupportedbynearly*allmodernOpera9ngSystems
• Whatdoyouneedtosupportconcurrency?– Don’twanttoforceapplica9onstodealwithit– We’dliketohavesomewayforOStorepresent(perhapsthrougha
programmingabstrac9on)ajobortask
Process
• AprocessisthechosenOSabstrac9onforajob/task– Unitofexecu9on– Unitofscheduling– Unitofaccoun9ng
• Aprocessistheinstan9a9onofaprogram– Allprocessesareassociatedwithaprogram– Aprogramorapplica9oncanhavemul9pleprocesses
What’sinaProcess?
Stack
Heap
DataSegment
TextSegment
SP
PC
0x00…….(Star9ngAddress)
0xFFF…..(EndingAddress)
AddressSpaceProgramstate• Addressspace• Code
• Data
• Stack
• Registers(SP,PC,FP,..)
ProgramIden9fier(PID)
WhatisinaProcess(2)?
• ProgramInforma9on
• Opera9ngSystemresources– Openfiles,opennetworksockets
• Execu9onstate– Running:currentlyusingtheCPU– Ready:readytousetheCPU(wai9ngforit)
• AnotherprocesshasCPU– Wai9ng:wai9ngforanevent(nottheCPU)suchasI/O
• Cannotmakeprogressun9lsignaled
UnixProcesses:pscommand
ProcessID Processexecu9onstate
Whatstatedoyouthinkprocessesareinmostofthe9me?
ProcessRepresenta9on
• TheOSrepresentsaprocessinthekernelusingaProcessControlBlock(PCB)– Programinforma9on– OSresources– Execu9onstate– Memorymanagement
– Schedulinginforma9on
– Accoun9nginforma9on
• ProcessControlBlocksarelarge– referredtoasheavyweightabstrac9ons– Containseverythingneededtorestorethehardwaretothestatethat
itwasinwhentheprocesswaslastrunning.
ProcessTransi9ons
Running
Wai9ng
Ready
scheduleprocess
unscheduleprocess
blockingonevent(I/O)
eventoccurred(e.g.,I/Oreceived)
When/howdoesaprocesschangeexecu9onstate?
ProcessTransi9ons
• Arunningprocesshashardwarestate– Registers,memorymanagement– Whathappenstothisstatewhenittransi9onstootherstate?
• IftheOSmovesaprocessoutofrunningstate– ItshardwarestatemustbesavedinthePCB
• IftheOSmovesaprocessintotherunningstate– ItshardwarestateisloadedintothePCB
• Theprocessofchangingthehardwarestatefromoneprocesstoanotherisacontextswitch– Contextswitchescanoccurasmanyas100‐10009mes/sec
ContextSwitchTwoprocesses:P0andP1
TheOSconsumesafairamountofprocessing9me
This9meisreferredtoascontextswitchingoverhead
Toomuchcontextswitchingoverheadisabadthing(why?)
Note:imagecourtesyofSilberschatz,2005
SchedulingQueuesTheOSkeepstrackofnon‐runningprocessesinschedulingqueues
head
tail
ReadyqueueFirefoxPCB XServerPCB IdlePCB
head
tail
DiskI/OPCBEmacsPCB BashPCB
TerminalPCBTheremaybemanywaitqueues
• seeNachos.threads.ThreadedQueue
PCB’sandStateQueues
• PCB’saredatastructuresdynamicallyallocatedinOSmemory
• Whenaprocessiscreated,theOSallocatesaPCBforit,ini9alizesit,andplacesitintheReadyqueue.
• Astheprocessexecutes,doesI/O,etc.,itsPCBismovedfromonequeuetoanother.
• Whentheprocessterminates,it’sPCBisdeallocated.
ProcessCrea9on
• Aprocessiscreatedbyanotherprocess– Createdprocessiscalledchild– Crea9ngprocessiscalledparent– InUnix,parentprocessIDisstoredasPPID
• parent‐childrela9onships:sshd‐>shell‐>ps
ProcessCrea9on(2)
• Howareparentandchildprocessesrelated?– IsanyofthestatefromthePCBinherited?
– Unix:ProcessUIDisinherited,andchildreninheritparent’sprivileges
• Whatelsecanaparentdowithachild?– Parentcaninvokesystemcalltowaitforcomple9onofchild
– Parentcanalsoexecuteinparallelwithchild
ProcessCrea9oninUnix
• fork()systemcallisusedtocreateanewprocessint fork() – Createsandini9alizesanewPCB– Createsanewaddressspace– Fillschild’saddressspacewithacopyoftheparent’sen9re
addressspace– Ini9alizeskernelresourcestopointtoparent’s– PutsPCBonthereadyqueue
• So…..howdoweknowwhichoneiswhich?– EachprocesshasadifferentPID– fork()returnstwice:
• child’sPIDtotheparent• “0”tothechild
Unixfork()exampleint main(int argc, char *argv[]) { char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) { printf(“Child of %s is %d\n”, name, getpid()); return 0; } else { printf(“My child is %d\n”, child_pid); return 0; { }
Whatdoesthisprogramprint?
Note:ThisexamplecourtesyofAlexSnoeren
int main(int argc, char *argv[]) {
char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) {
printf(“Child of %s is %d\n”, name, getpid());
return 0; }
else { printf(“My child is %d\n”, child_pid); return 0;
{ }
int main(int argc, char *argv[]) {
char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) {
printf(“Child of %s is %d\n”, name, getpid());
return 0; }
else { printf(“My child is %d\n”, child_pid); return 0;
{ }
Unixfork()example(3)Parent Child
PC PC
int main(int argc, char *argv[]) {
char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) {
printf(“Child of %s is %d\n”, name, getpid());
return 0; }
else { printf(“My child is %d\n”, child_pid); return 0;
{ }
int main(int argc, char *argv[]) {
char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) {
printf(“Child of %s is %d\n”, name, getpid());
return 0; }
else { printf(“My child is %d\n”, child_pid); return 0;
{ }
Unixfork()example(4)Parent Child
PC PC
Pid=27766 Pid=0
int main(int argc, char *argv[]) {
char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) {
printf(“Child of %s is %d\n”, name, getpid());
return 0; }
else { printf(“My child is %d\n”, child_pid); return 0;
{ }
int main(int argc, char *argv[]) {
char *name = argv[0]; int child_pid = fork(); if (child_pid == 0) {
printf(“Child of %s is %d\n”, name, getpid());
return 0; }
else { printf(“My child is %d\n”, child_pid); return 0;
{ }
Unixfork()example(5)Parent ChildPid=27766 Pid=0
Mychildis27766 Childofforktestis27766
fork()Abstrac9on
while (1) {
int sock = accept();
if (child_pid == 0) { // handle client request
…
}
else {
// close socket
…
{
}
Note:ThisexamplecourtesyofAlexSnoeren
Veryusefulif• Childiscoopera9ngwithparent• Childsharesstatewithparent
Webserverexample
Processsynchroniza9oninUnix
• wait()suspendsthecurrentprocessun9lachildprocessendsintwait(int*status)
– wait()returns‐1iferrororpidofchild– statusischild’sexitstatus
• Whatifparentprocessexitsbeforechild?– PCBofchildprocessremains
– Childprocessbecomesan“orphan”or“zombie”process
Unixfork()andwait()exampleint main(int argc, char *argv[]) {
char *name = argv[0];
int child_pid = fork();
int rv, status;
if (child_pid == 0) {
printf(“Child of %s is %d\n”, name, getpid());
return 0;
}
else {
rv = wait(&status);
printf(“My child is %d, rv=%d, status=%d\n”, child_pid, rv, status);
return 0;
{
} Whatdoesthisprogramprint?
Note:ThisexamplecourtesyofAlexSnoeren
Processcrea9oninUnix(2)
• exec()systemcallusedtostopand“restart”processint exec(char *prog, char *argv[]) – Stopsthecurrentprocess– Loadsprogramprogintoexis9ngaddressspace– Reini9alizeshardwarestate– PutsPCBonthereadyqueue
• Whatshouldexec()return?– Whatabout“execcsh”?– “execls”?
UnixShells
while(1){
char*cmd=read_command();
intchild_pid=fork();if(child_pid==0){
ManipulateSTDIN/OUT/ERRfiledescriptorsforpipes,redirec=on,etc.
exec(cmd);
panic(“execfailed”);
}else{
waitpid(child_pid);
}
}
ProcessTermina9on
• exit(intstatus)systemcallterminatesprocess– exit()freesallresourcesconsumedbyprocess
• Close/releaseallOSresources• Freeallocatedmemory
• Terminateanythreads(nextlecture)
• RemoveanddeletePCB
• NotethattheOSdoesnotassumethataprocesswillfreeeverythingabove.– Why?
ProcessTransi9ons
Running
Wai9ng
Ready
scheduleprocess
unscheduleprocess
blockingonevent(I/O)
eventoccurred(e.g.,I/Oreceived)
processexit
New
Terminated
createprocess
InterprocessCommunica9on
• Wecancreateprocesswithfork(),buthowdowegetthemtoworktogether?– Wanttopassinforma9onbetweenprocesses.
• Childgetsacopyofparent’saddressspace.– Whatiftheyneedtocommunicateaterfork()?
• Whathappensifsiblingprocesseswanttocommunicate?
InterprocessCommunica9on(IPC)
• Opera9ngSystemneedstoprovidesupport– Why?
• OSmechanisms:– SharedMemory– MessagePassing
SharedMemoryProcessesreadandwritetoaregionofsharedmemory
ProcessA
ProcessB
PhysicalMemory
Kernel
• Aprocessneedstocreateasharedmemorysegment• Unix:shmget()syscall• Kernelcreatessharedmemory
• Eachprocessneedstoaeachtothissegment• Unix:shmat()syscall
• Eitherprocesscanreadorwritetothisregion• A:sprinu(shared_mem,“helloworld”);
• B:prinu(“%s\n”,shared_mem);
helloworld
helloworld(stdout)
shared_mem
MessagePassing
• Createacommunica9onlinkbetweenAandB– OScancreatemailboxfor
indirectcommunica9on– Useothermeansfordirect
communica9on(sharedmemory,network,bus)
• send(B,message)– Doesitwaitun9lreceived?
• receive(A,message)– Doesitwaitun9lavailable?
• Synchroniza9on– Blocking/Synchronous– Non‐Blocking/Asynchronous
ProcessA
ProcessB
Kernel
ProcessespassmessagesthroughOS
InterprocessCommunica9on
• Eachcoopera9ngmustknowthenameoftheother• SharedMemory
– Canperformfrequentandlargetransfers– Mustsynchronize
• MessagePassing– Noexplicitneedforsynchroniza9on– Kerneloverheadpermessage
• Othercommonvaria9onsofIPC– Unixpipes(e.g.,“ls|wc”)– WindowsLocalProcedureCalls(LPCs)
InterprocessCommunica9on
• WhousesIPCmechanisms?– Parallelprograms(e.g.,Webserver,stagedcomputa9ons)– Modularprograms(i.e.,composetogethersubtasks,eachbeingaseparateprocesses)
• Ingeneral,IPCmechanismsare9me‐consuming– Involvesystemcalls(kernelinvolved)
– Processesneedtocontextswitchtosend/receivemessages
Summary
• Whatarethebasicunitsofexecu9oninanOS?– Aprocess
• Howaretheseunitsofexecu9onstoredandmanagedinanOS?– PCBsandinSchedulingQueues
• Whatarethepossiblestatesofaprocess?– Running,ready,wai9ng,new,terminated
• Howdoprocessestransi9onfromstatetostate?– Schedulingevents,I/Osignals,processcrea9on,termina9on
• Howdoprocesscommunicate?– SharedmemoryorMessagePassing