CSE506:Opera.ngSystems
SignalsandInter-ProcessCommunica.on
DonPorter
1
CSE506:Opera.ngSystems
Housekeeping• Paperreadingassignedfornextclass
2
CSE506:Opera.ngSystems
LogicalDiagram
MemoryManagement
CPUScheduler
User
Kernel
Hardware
BinaryFormats
Consistency
SystemCalls
Interrupts Disk Net
RCU FileSystem
DeviceDrivers
Networking Sync
MemoryAllocators Threads
Today’sLectureProcess
CoordinaKon
3
CSE506:Opera.ngSystems
LastKme…• We’vediscussedhowtheOSschedulestheCPU– Andhowtoblockaprocessonaresource(disk,network)
• Today:– Howdoprocessesblockoneachother?– Andmoregenerallycommunicate?
4
CSE506:Opera.ngSystems
Outline• Signals– OverviewandAPIs– Handlers– Kernel-leveldelivery– Interruptedsystemcalls
• InterprocessCommunicaKon(IPC)– PipesandFIFOs– SystemVIPC– WindowsAnalogs
5
CSE506:Opera.ngSystems
Whatisasignal?• Likeaninterrupt,butforapplicaKons– <64numberswithspecificmeanings– Aprocesscanraiseasignaltoanotherprocessorthread– AprocessorthreadregistersahandlerfuncKon
• ForbothIPCanddeliveryofhardwareexcepKons– ApplicaKon-levelhandlers:divzero,segfaults,etc.
• No“message”beyondthesignalwasraised– Andmaybealialemetadata
• PIDofsender,faulKngaddress,etc.• Butplaborm-specific(non-portable)
6
CSE506:Opera.ngSystems
Example
Pid300
int main() { ... signal(SIGUSR1, &usr_handler); ...
}
Registerusr_handler()tohandleSIGUSR1 7
CSE506:Opera.ngSystems
Example
Pid300
kill(300, SIGUSR1);
SendsignaltoPID300
Pid400
int main() { ...
} int usr_handler() { …
PC
8
CSE506:Opera.ngSystems
BasicModel• ApplicaKonregistershandlerswithsignalorsigacKon• Sendsignalswithkillandfriends– OrraisedbyhardwareexcepKonhandlersinkernel
• Signaldeliveryjumpstosignalhandler– Irregularcontrolflow,similartoaninterrupt
APInamesareadmiaedlyconfusing 9
CSE506:Opera.ngSystems
SignalTypes• Seeman7signalforthefulllist:(variesbysys/arch)SIGTSTP–1–Stoptypedatterminal(Ctrl+Z)SIGKILL–9–Killaprocess,forrealziesSIGSEGV–11–SegmentaKonfaultSIGPIPE–13–Brokenpipe(writewithnoreaders)SIGALRM–14–TimerSIGUSR1–10–User-definedsignal1SIGCHLD–17–ChildstoppedorterminatedSIGSTOP–19–StopaprocessSIGCONT–18–ConKnueifstopped
10
CSE506:Opera.ngSystems
LanguageExcepKons• SignalsaretheunderlyingmechanismforExcepKonsandcatchblocks
• JVMorotherrunKmesystemsetssignalhandlers– SignalhandlercausesexecuKontojumptothecatchblock
11
CSE506:Opera.ngSystems
SignalHandlerControlFlow
This is the Title of the Book, eMatter EditionCopyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Delivering a Signal | 443
starts executing the signal handler, because the handler’s starting address was forcedinto the program counter. When that function terminates, the return code placed onthe User Mode stack by the setup_frame( ) or setup_rt_frame() function is exe-cuted. This code invokes the sigreturn( ) or the rt_sigreturn() system call; the cor-responding service routines copy the hardware context of the normal program to theKernel Mode stack and restore the User Mode stack back to its original state (byinvoking restore_sigcontext( )). When the system call terminates, the normal pro-gram can thus resume its execution.
Let’s now examine in detail how this scheme is carried out.
Setting up the frame
To properly set the User Mode stack of the process, the handle_signal( ) functioninvokes either setup_frame( ) (for signals that do not require a siginfo_t table; seethe section “System Calls Related to Signal Handling” later in this chapter) or setup_rt_frame( ) (for signals that do require a siginfo_t table). To choose among thesetwo functions, the kernel checks the value of the SA_SIGINFO flag in the sa_flags fieldof the sigaction table associated with the signal.
The setup_frame( ) function receives four parameters, which have the followingmeanings:
sigSignal number
kaAddress of the k_sigaction table associated with the signal
oldsetAddress of a bit mask array of blocked signals
Figure 11-2. Catching a signal
Normalprogram
flow
Signalhandler
Return codeon the stack
do_signal()
handle_signal()
setup_frame()
system_call()
sys_sigreturn()
restore_sigcontext()
User Mode Kernel Mode
FromUnderstandingtheLinuxKernel 12
CSE506:Opera.ngSystems
AlternateStacks• SignalhandlersexecuteonadifferentstackthanprogramexecuKon.– Why?
• Safety:Appcanensurestackisactuallymapped– AndavoidassumpKonsaboutapplicaKonnotusingspacebelowrsp
– Setwithsigaltstack()systemcall
• Likeaninterrupthandler,kernelpushesregisterstateoninterruptstack– Returntokernelwithsigreturn()systemcall– Appcanchangeitsownon-stackregisterstate!
13
CSE506:Opera.ngSystems
NestedSignals• Whathappenswhenyougetasignalinthesignalhandler?
• Andwhyshouldyoucare?
14
CSE506:Opera.ngSystems
TheProblemwithNesKngint main() {
/* ... */ signal(SIGINT, &handler); signal(SIGTERM, &handler); /* ... */
} int handler() {
free(buf1); free(buf2);
}
SIGINT
SIGTERM
SignalStack
PC Callsmunmap()
Anothersignaldeliveredon
returnDoublefree!
15
CSE506:Opera.ngSystems
NestedSignals• Theoriginalsignal()specificaKonwasatotalmess!– Nowdeprecated---donotuse!
• NewsigacKon()APIletsyouspecifythisindetail– Whatsignalsareblocked(anddeliveredonsigreturn)– Similartodisablinghardwareinterrupts
• Asyoumightguess,blockingsystemcallsinsideofasignalhandlerareonlysafewithcarefuluseofsigacKon()
16
CSE506:Opera.ngSystems
ApplicaKonvs.Kernel• App:signalsappeartobedeliveredroughlyimmediately
• Kernel(lazy):– Sendasignal==markapendingsignalinthetask
• AndmakerunnableifblockedwithTASK_INTERRUPTIBLEflag
– Checkpendingsignalsonreturnfrominterruptorsyscall• Deliverifpending
17
CSE506:Opera.ngSystems
Example
Pid300RUNNING
kill(300, SIGUSR1);
SendsignaltoPID300
Pid400
int main() { read();
} int usr_handler() { …
PC
…
…10Pid300
INTERRUPTIBLE
Blockondisk
read!
Markpendingsignal,unblock
Whathappenstoread?
18
CSE506:Opera.ngSystems
InterruptedSystemCalls• IfasystemcallblocksintheINTERRUPTIBLEstate,asignalwakesitup
• Yetsignalsaredeliveredonreturnfromasystemcall• Howisthisresolved?• Thesystemcallfailswithaspecialerrorcode– EINTRandfriends– Manysystemcallstransparentlyretryaversigreturn– Somedonot–checkforEINTRinyourapplicaKons!
19
CSE506:Opera.ngSystems
Defaulthandlers• Signalshavedefaulthandlers:– Ignore,kill,suspend,conKnue,dumpcore– Theseexecuteinsidethekernel
• Installingahandlerwithsignal/sigacKonoverridesthedefault
• Afew(SIGKILL)cannotbeoverridden
20
CSE506:Opera.ngSystems
RTSignals• Defaultsignalsareonlyin2states:signaledornot– IfIsend2SIGUSR1’stoaprocess,onlyonemaybedelivered
– IfsystemisslowandIfuriouslyhitCtrl+Coverandover,onlyoneSIGINTdelivered
• RealKme(RT)signalskeepacount– Deliveronesignalforeachonesent
21
CSE506:Opera.ngSystems
SignalSummary• AbstracKonlikehardwareinterrupts– Somecaremustbetakentoblockotherinterrupts– EasytowritebuggyhandlersandmissEINTR
• UnderstandcontrolflowfromapplicaKonandkernelperspecKve
• UnderstandbasicAPIs
22
CSE506:Opera.ngSystems
OtherIPC• Pipes,Sockets,andFIFOs• SystemVIPC• Windowscomparison
23
CSE506:Opera.ngSystems
Pipes• Streamofbytesbetweentwoprocesses• Readandwritelikeafilehandle– Butnotanywhereinthehierarchicalfilesystem– Andnotpersistent– Andnocursororseek()-ing– Actually,2handles:areadhandleandawritehandle
• Primarilyusedforparent/childcommunicaKon– Parentcreatesapipe,childinheritsit
24
CSE506:Opera.ngSystems
Exampleint pipe_fd[2]; int rv = pipe(pipe_fd); int pid = fork(); if (pid == 0) {
close(pipe_fd[1]); //Close unused write end dup2(pipe_fd[0], 0); // Make the read end stdin exec(“grep”, “quack”);
} else { close (pipe_fd[0]); // Close unused read end …
25
CSE506:Opera.ngSystems
FIFOs(akaNamedPipes)• ExisKngpipescan’tbeopened---onlyinherited– OrpassedoveraUnixDomainSocket(beyondtoday’slec)
• FIFOs,orNamedPipes,addaninterfaceforopeningexisKngpipes
26
CSE506:Opera.ngSystems
Sockets• Similartopipes,exceptfornetworkconnecKons• SetupandconnecKonmanagementisabittrickier– Atopicforanotherday(orclass)
27
CSE506:Opera.ngSystems
Select• WhatifIwanttoblockunKloneofseveralhandleshasdatareadytoread?
• Readwillblockononehandle,butperhapsmissdataonasecond…
• SelectwillblockaprocessunKlahandlehasdataavailable– UsefulforapplicaKonsthatusepipes,sockets,etc.
28
CSE506:Opera.ngSystems
SynthesisExample:TheShell• Almostall‘commands’arereallybinaries– /bin/ls
• KeyabstracKon:RedirecKonoverpipes– ‘>’,‘<‘,and‘|’implementedbytheshellitself
29
CSE506:Opera.ngSystems
ShellExample• Ex:ls | grep foo • ImplementaKonsketch:– ShellparsestheenKrestring– Setsupchainofpipes– Forksandexec’s‘ls’and‘grep’separately– Waitonoutputfrom‘grep’,printtoconsole
30
CSE506:Opera.ngSystems
Jobcontrolinashell• Shellkeepsitsown“scheduler”forbackgroundprocesses• Howto:– Putaprocessinthebackground?
• SIGTSTPhandlercatchesCtrl-Z• SendSIGSTOPtocurrentforegroundchild
– ResumeexecuKon(fg)?• SendSIGCONTtopausedchild,usewaitpid()toblockunKlfinished
– Executeinbackground(bg)?• SendSIGCONTtopausedchild,butblockonterminalinput
31
CSE506:Opera.ngSystems
Otherhints• Splice(),tee(),andsimilarcallsareusefulforconnecKngpipestogether– Avoidscopyingdataintoandout-ofapplicaKon
32
CSE506:Opera.ngSystems
SystemVIPC• Semaphores–Lock• MessageQueues–Likeamailbox,“small”messages• SharedMemory–parKcularlyuseful– Aregionofnon-COWanonymousmemory– Mapatagivenaddressusingshmat()
• CanpersistlongerthananapplicaKon– Mustbeexplicitlydeleted– Canleakatsystemlevel– Butclearedaverareboot
33
CSE506:Opera.ngSystems
SystemVKeysandIDs• Programmerspickarbitrary32-bitkeys– UsethesekeystonamesharedabstracKons
• Findakeyusingshmget(),msgget(),etc.– Kernelinternallymapskeytoa32-bitID
34
CSE506:Opera.ngSystems
WindowsComparison• HardwareexcepKonsaretreatedseparatelyfromIPC– Upcallstontdll.dll(libcequivalent),tocallhandlers
• AllIPCtypescanberepresentedashandles– ProcessterminaKon/suspend/resumesignaledwithprocesshandles
– SignalscanbeanEventhandle– SemaphoresandMutexeshavehandles– Sharedmemoryequallycomplicated(butsKllhandles)
• Singleselect()-likeAPItowaitonahandletobesignaled
35
CSE506:Opera.ngSystems
Summary• Understandsignals• Understandhigh-levelproperKesofpipesandotherUnixIPCabstracKons– High-levelcomparisonwithWindows
36