Lecture4-Processescpoellab/teaching/cse30341/Lecture4... · 2016-01-22 · Process Switching...
Transcript of Lecture4-Processescpoellab/teaching/cse30341/Lecture4... · 2016-01-22 · Process Switching...
1/20/16
1
CSE30341Opera,ngSystemPrinciples
Lecture4–Processes
Recap–LastLecture
• Opera,ngSystemServices• SystemCallsandInterrupts• SystemPrograms• Opera,ngSystemDesignandImplementa,on• SystemLayering• VirtualMachines
CSE30341-Opera,ngSystemPrinciples 2
1/20/16
2
Overview
• ProcessConcepts• ProcessScheduling• Opera,onsonProcesses• Inter-processCommunica,on
CSE30341-Opera,ngSystemPrinciples 3
ProcessConcept
• Job/Process/Taskusedinterchangeably• Aprocessisaninstanceofaprogram(“programinexecu,on”)
• Program:“pieceofcode”• Process:code+data+moredata+controlstructures+…
CSE30341-Opera,ngSystemPrinciples 4
1/20/16
3
ProcessMemoryLayout
CSE30341-Opera,ngSystemPrinciples 5
• Stack:TemporaryData• Func,onparameters,localvariables,func,oncallframes.
• Heap:Dynamicallyallocatedmemory.
• Data:Globalvariables&constantstrings.
• Text:Programcode.
Process“LifeCycle”
CSE30341-Opera,ngSystemPrinciples 6
NEW
READY RUNNING
TERMINATED
WAITING
admibed
Interrupt
exit
Schedulerdispatch
I/OoreventwaitI/Ooreventcomple,on
1/20/16
4
ProcessState
• Aprocesschangesstateconstantly:– New:beingcreated.– Running:runningonaprocessorcore.– WaiAng:wai,ngforanevent.– Ready:(orrunnable)wai,ngforacore.– Terminated:finished/dead.
CSE30341-Opera,ngSystemPrinciples 7
OSInforma,onaboutProcesses
• Memory(Stack,Heap,Code,Sta,cData)• CurrentState(e.g.,programcounter)• ProcessID• SavedRegisters• OpenFiles• OtherbookkeepingdataThisiscalledtheprocesscontrolblock(PCB)or
taskcontrolblock(TCB).
CSE30341-Opera,ngSystemPrinciples 8
1/20/16
5
ProcessControlBlock
CSE30341-Opera,ngSystemPrinciples 9
PCBonLinux
CSE30341-Opera,ngSystemPrinciples 10
1/20/16
6
CSE30341-Opera,ngSystemPrinciples 11
CSE30341-Opera,ngSystemPrinciples 12
1/20/16
7
ProcessSwitching(“ContextSwitch”)
CSE30341-Opera,ngSystemPrinciples 13
Process“Wait”Queues
• JobQueueisallprocessesonthesystem.• ReadyQueue(RunQueue)containsprocesseswai,ngtorun,orwaiAngfortheCPU!
• DeviceQueueprocesseswai,ngforadeviceevent(“blocked”devices).
• “Other”Queuescontainprocesseswai,ngforotherprocessestofinish,sleepingfor,me,etc.
CSE30341-Opera,ngSystemPrinciples 14
1/20/16
8
Process“Wait”Queues
CSE30341-Opera,ngSystemPrinciples 15
Schedulers
• Long-termschedulerwhichprocessesshouldberuninthefuture?– Degreeofmul,programming!
• Short-termschedulerwhichprocessshouldberunnext?– Managesqueuesandquicklydecidesnextprocesstorun.
CSE30341-Opera,ngSystemPrinciples 16
1/20/16
9
SchedulingConcerns
• IsenoughRAMavailabletosa,sfyrunningprocesses?
• IsdevicethroughputabletosupportmoreIO-boundprocesses?
• IsthereenoughCPU,meavailabletosa,sfyallprocesses?(long)HowdoIschedulefairly?(short)
• Aretherebenefitsforsleeping(swapping)aprocessforanextendedAme?(long)
CSE30341-Opera,ngSystemPrinciples 17
Schedulers
• Short-term:invokedfrequently(milliseconds);mustbefast
• Long-term:infrequently(seconds)• I/O-boundprocess:spendsmore,medoingI/Othanprocessing(CPUburstscanbefrequent,butareshort)
• CPU-bound:spendsmore,medoingcomputa,ons(verylongCPUbursts)
CSE30341-Opera,ngSystemPrinciples 18
1/20/16
10
“Medium”Scheduling
CSE30341-Opera,ngSystemPrinciples 19
ProcessCrea,on
• Aprocessisalwayscreatedviaaparent,exceptforprocess1,/sbin/init.
• Aparentcanhavemul,plechildren.En,restructureisatree.
• Eachprocesshasauniqueiden,fier,theprocessidenAfier,orpid(getthepidofaprocessusingthegetpid()systemcall).
CSE30341-Opera,ngSystemPrinciples 20
1/20/16
11
CSE30341-Opera,ngSystemPrinciples 21
CSE30341-Opera,ngSystemPrinciples 22
1/20/16
12
CSE30341-Opera,ngSystemPrinciples 23
ProcessCrea,on• Resourcesharing
1. Parentandchildrenshareallresources2. Childrensharesubsetofparent’sresources3. Parentandchildsharenoresources
• ExecuAon1. Parentandchildrenexecuteconcurrently2. Parentwaitsun,lchildrenterminate
• Addressspace1. Childisduplicateofparent2. Childhasaprogramloadedintoit
CSE30341-Opera,ngSystemPrinciples 24
1/20/16
13
UNIXProcessCrea,on
• UNIXexamples– forksystemcallcreatesnewprocess– execsystemcallusedaperaforktoreplacetheprocess’memoryspacewithanewprogram
CSE30341-Opera,ngSystemPrinciples 25
ExampleCode#include <sys/types.h> #include <stdio.h> #include <unistd.h> int main() { pid_t pid; /* fork another process */ pid = fork(); if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed"); return 1; } else if (pid == 0) { /* child process */ execlp("/bin/ls", "ls", NULL); } else { /* parent process */ /* parent will wait for the child */ wait (NULL); printf ("Child Complete"); } return 0;
}
CSE30341-Opera,ngSystemPrinciples 26
1/20/16
14
ProcessTermina,on• Process executes last statement and then asks the operating
system to delete it using the exit() system call.– Returns status data from child to parent (via wait())– Process’ resources are deallocated by operating system
• Terminate a process from another process: SIGKILL (kill -9 pid)
• Parent may terminate the execution of children processes using the abort() system call. Some reasons for doing so:– Child has exceeded allocated resources– Task assigned to child is no longer required– The parent is exiting and the operating systems does not allow
a child to continue if its parent terminates
CSE30341-Opera,ngSystemPrinciples 27
ProcessTermina,on• What happens if a process “dies”?
– The parent process may wait for termination of a child process by using the wait()system call. The call returns status information and the pid of the terminated process: pid = wait(&status);
– Parent “collects” child’s resources – If no parent waiting (did not invoke wait()) process is a
zombie• What happens if parent “dies”?
– If parent terminated without invoking wait, process is an orphan
– May receive “new parent” (grandparent, init process, etc.)– Cascading termination: no orphans allowed; if a process
terminates, all its children must also be terminated
CSE30341-Opera,ngSystemPrinciples 28
1/20/16
15
InterprocessCommunica,on
• Processescommunicatebysharingdata.• Whydoprocessescommunicate?– Computa,onspeedup– Modularity– Informa,onsharing
• Mechanism:interprocesscommunicaAon(IPC)
• Twostandardmodels:SharedMemoryandMessagePassing
CSE30341-Opera,ngSystemPrinciples 29
Communica,onModels
CSE30341-Opera,ngSystemPrinciples 30
MessagePassing SharedMemory
process A
message queue
kernel
(a) (b)
process A
shared memory
kernel
process B
m0 m1 m2 ...m3 mn
process B
1/20/16
16
Producer-ConsumerProblem
• Oneprocessproducesdata.Thesecondprocessconsumesthedata.
• Datastoredinabuffer:– Unbounded-Bufferhasnolimitonsize.Growstosizeofmemory.
– Bounded-Bufferhasfixedsize.Createsanewproblem:• HowdowehandletheproducercreaAngdatatoofast?
CSE30341-Opera,ngSystemPrinciples 31
SharedMemorySolu,on
Circularbuffer
CSE30341-Opera,ngSystemPrinciples 32
OUTIN
NUL NUL NUL NUL NUL NUL NUL NUL NUL
IN=OUT->EMPTY
OUT IN
A NUL NUL NUL NUL NUL NUL NUL NUL
OUT IN
NUL NUL C D E F NUL NUL NUL
1/20/16
17
SharedMemorySolu,on• Shared data
#defineBUFFER_SIZE10typedefstruct{...}item;itembuffer[BUFFER_SIZE];intin=0;intout=0;
• Solution is correct, but can only use BUFFER_SIZE-1 elements
CSE30341-Opera,ngSystemPrinciples 33
BoundedBuffer-Producer
itemnext_produced;while(true){
/*produceaniteminnextproduced*/while(((in+1)%BUFFER_SIZE)==out) ;/*donothing*/buffer[in]=next_produced;in=(in+1)%BUFFER_SIZE;
}
CSE30341-Opera,ngSystemPrinciples 34
1/20/16
18
BoundedBuffer-Consumer
itemnext_consumed;while(true){
while(in==out) ;/*donothing*/
next_consumed=buffer[out];out=(out+1)%BUFFER_SIZE;
/*consumetheiteminnextconsumed*/
}
CSE30341-Opera,ngSystemPrinciples 35
MessagePassing
• Twoprimi,ves:– send(C,message)–messageshavemaximumsize– receive(P,message)
• Thinkmailboxes.• Kernelusuallymanagesthemessagepassingand“mailboxes”.
CSE30341-Opera,ngSystemPrinciples 36
1/20/16
19
MessagePassingConsidera,ons
• Howisthelinkestablished?– Automa,callyonsend?
• Canthelinkbeasymmetric?– Receivingamessage:whoisthesender?
• Istherealimittothecapacityofthelink?• Isthemessagesizefixedorvariable?• Isalinkunidirec,onalorbidirec,onal?• Cantherebemul,plelinksbetweenapairofcommunica,onprocesses?
CSE30341-Opera,ngSystemPrinciples 37
MessagePassing
• DirectCommunica,on– send(P,message)->receiverprocessP– receive(Q,message)->senderprocessQ
• IndirectCommunica,on(“mailboxes”)– send(M1,message)->putinmailboxM1– receive(M1,message)->takefrommailboxM1
CSE30341-Opera,ngSystemPrinciples 38
1/20/16
20
IPCSynchroniza,on
• Blocking?– Consumerisputinawai,ngschedulerqueueif“mailbox”isempty.
– Producerisputinawai,ngschedulerqueueif“mailbox”isfull.
• Non-blocking?– NeitherProducernorConsumerblocks;failureisreturnedfrommessagepassingprimi,veinstead.
CSE30341-Opera,ngSystemPrinciples 39
Buffering
• Queue of messages attached to the link; implemented in one of three ways:– Zero capacity – no messages are queued on
a link. Sender must wait for receiver (rendezvous)
– Bounded capacity – finite length of n messages. Sender must wait if link full
– Unbounded capacity – infinite length. Sender never waits
CSE30341-Opera,ngSystemPrinciples 40
1/20/16
21
IPC-POSIX
• POSIXSharedMemoryshm_id = shm_open(name, O CREAT | O RDWR, 0666); ftruncate(shm_id, 4096); shared_memory = (char *) shmat(shm_id, NULL, 0); sprintf(shared_memory, "Writing to shared memory"); Also: shmdt (remove), shmctl (destroy)
CSE30341-Opera,ngSystemPrinciples 41
IPC-Mach
• Mach communication is message based– Even system calls are messages– Each task gets two mailboxes at creation- Kernel
and Notify– Only three system calls needed for message
transfer msg_send(), msg_receive(), msg_rpc() – Mailboxes needed for communication, created via port_allocate()
CSE30341-Opera,ngSystemPrinciples 42
1/20/16
22
Recap
• KeyPoints:– SystemLayering– ConceptofaProcess– Scheduling– ProcessCrea,onandTermina,on– InterprocessCommunica,on
CSE30341-Opera,ngSystemPrinciples 43