Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang...

36
CSE 506: Opera.ng Systems Signals and Inter-Process Communica.on Don Porter 1

Transcript of Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang...

Page 1: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

SignalsandInter-ProcessCommunica.on

DonPorter

1

Page 2: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Housekeeping•  Paperreadingassignedfornextclass

2

Page 3: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

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

Page 4: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

LastKme…•  We’vediscussedhowtheOSschedulestheCPU–  Andhowtoblockaprocessonaresource(disk,network)

•  Today:–  Howdoprocessesblockoneachother?–  Andmoregenerallycommunicate?

4

Page 5: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Outline•  Signals–  OverviewandAPIs–  Handlers–  Kernel-leveldelivery–  Interruptedsystemcalls

•  InterprocessCommunicaKon(IPC)–  PipesandFIFOs–  SystemVIPC– WindowsAnalogs

5

Page 6: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

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

Page 7: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Example

Pid300

int main() { ... signal(SIGUSR1, &usr_handler); ...

}

Registerusr_handler()tohandleSIGUSR1 7

Page 8: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Example

Pid300

kill(300, SIGUSR1);

SendsignaltoPID300

Pid400

int main() { ...

} int usr_handler() { …

PC

8

Page 9: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

BasicModel•  ApplicaKonregistershandlerswithsignalorsigacKon•  Sendsignalswithkillandfriends–  OrraisedbyhardwareexcepKonhandlersinkernel

•  Signaldeliveryjumpstosignalhandler–  Irregularcontrolflow,similartoaninterrupt

APInamesareadmiaedlyconfusing 9

Page 10: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

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

Page 11: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

LanguageExcepKons•  SignalsaretheunderlyingmechanismforExcepKonsandcatchblocks

•  JVMorotherrunKmesystemsetssignalhandlers–  SignalhandlercausesexecuKontojumptothecatchblock

11

Page 12: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

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

Page 13: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

AlternateStacks•  SignalhandlersexecuteonadifferentstackthanprogramexecuKon.– Why?

•  Safety:Appcanensurestackisactuallymapped–  AndavoidassumpKonsaboutapplicaKonnotusingspacebelowrsp

–  Setwithsigaltstack()systemcall

•  Likeaninterrupthandler,kernelpushesregisterstateoninterruptstack–  Returntokernelwithsigreturn()systemcall–  Appcanchangeitsownon-stackregisterstate!

13

Page 14: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

NestedSignals•  Whathappenswhenyougetasignalinthesignalhandler?

•  Andwhyshouldyoucare?

14

Page 15: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

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

Page 16: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

NestedSignals•  Theoriginalsignal()specificaKonwasatotalmess!–  Nowdeprecated---donotuse!

•  NewsigacKon()APIletsyouspecifythisindetail– Whatsignalsareblocked(anddeliveredonsigreturn)–  Similartodisablinghardwareinterrupts

•  Asyoumightguess,blockingsystemcallsinsideofasignalhandlerareonlysafewithcarefuluseofsigacKon()

16

Page 17: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

ApplicaKonvs.Kernel•  App:signalsappeartobedeliveredroughlyimmediately

•  Kernel(lazy):–  Sendasignal==markapendingsignalinthetask

•  AndmakerunnableifblockedwithTASK_INTERRUPTIBLEflag

–  Checkpendingsignalsonreturnfrominterruptorsyscall•  Deliverifpending

17

Page 18: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

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

Page 19: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

InterruptedSystemCalls•  IfasystemcallblocksintheINTERRUPTIBLEstate,asignalwakesitup

•  Yetsignalsaredeliveredonreturnfromasystemcall•  Howisthisresolved?•  Thesystemcallfailswithaspecialerrorcode–  EINTRandfriends– Manysystemcallstransparentlyretryaversigreturn–  Somedonot–checkforEINTRinyourapplicaKons!

19

Page 20: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Defaulthandlers•  Signalshavedefaulthandlers:–  Ignore,kill,suspend,conKnue,dumpcore–  Theseexecuteinsidethekernel

•  Installingahandlerwithsignal/sigacKonoverridesthedefault

•  Afew(SIGKILL)cannotbeoverridden

20

Page 21: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

RTSignals•  Defaultsignalsareonlyin2states:signaledornot–  IfIsend2SIGUSR1’stoaprocess,onlyonemaybedelivered

–  IfsystemisslowandIfuriouslyhitCtrl+Coverandover,onlyoneSIGINTdelivered

•  RealKme(RT)signalskeepacount–  Deliveronesignalforeachonesent

21

Page 22: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

SignalSummary•  AbstracKonlikehardwareinterrupts–  Somecaremustbetakentoblockotherinterrupts–  EasytowritebuggyhandlersandmissEINTR

•  UnderstandcontrolflowfromapplicaKonandkernelperspecKve

•  UnderstandbasicAPIs

22

Page 23: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

OtherIPC•  Pipes,Sockets,andFIFOs•  SystemVIPC•  Windowscomparison

23

Page 24: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Pipes•  Streamofbytesbetweentwoprocesses•  Readandwritelikeafilehandle–  Butnotanywhereinthehierarchicalfilesystem–  Andnotpersistent–  Andnocursororseek()-ing–  Actually,2handles:areadhandleandawritehandle

•  Primarilyusedforparent/childcommunicaKon–  Parentcreatesapipe,childinheritsit

24

Page 25: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

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

Page 26: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

FIFOs(akaNamedPipes)•  ExisKngpipescan’tbeopened---onlyinherited–  OrpassedoveraUnixDomainSocket(beyondtoday’slec)

•  FIFOs,orNamedPipes,addaninterfaceforopeningexisKngpipes

26

Page 27: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Sockets•  Similartopipes,exceptfornetworkconnecKons•  SetupandconnecKonmanagementisabittrickier–  Atopicforanotherday(orclass)

27

Page 28: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Select•  WhatifIwanttoblockunKloneofseveralhandleshasdatareadytoread?

•  Readwillblockononehandle,butperhapsmissdataonasecond…

•  SelectwillblockaprocessunKlahandlehasdataavailable–  UsefulforapplicaKonsthatusepipes,sockets,etc.

28

Page 29: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

SynthesisExample:TheShell•  Almostall‘commands’arereallybinaries–  /bin/ls

•  KeyabstracKon:RedirecKonoverpipes–  ‘>’,‘<‘,and‘|’implementedbytheshellitself

29

Page 30: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

ShellExample•  Ex:ls | grep foo •  ImplementaKonsketch:–  ShellparsestheenKrestring–  Setsupchainofpipes–  Forksandexec’s‘ls’and‘grep’separately– Waitonoutputfrom‘grep’,printtoconsole

30

Page 31: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Jobcontrolinashell•  Shellkeepsitsown“scheduler”forbackgroundprocesses•  Howto:–  Putaprocessinthebackground?

•  SIGTSTPhandlercatchesCtrl-Z•  SendSIGSTOPtocurrentforegroundchild

–  ResumeexecuKon(fg)?•  SendSIGCONTtopausedchild,usewaitpid()toblockunKlfinished

–  Executeinbackground(bg)?•  SendSIGCONTtopausedchild,butblockonterminalinput

31

Page 32: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Otherhints•  Splice(),tee(),andsimilarcallsareusefulforconnecKngpipestogether–  Avoidscopyingdataintoandout-ofapplicaKon

32

Page 33: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

SystemVIPC•  Semaphores–Lock•  MessageQueues–Likeamailbox,“small”messages•  SharedMemory–parKcularlyuseful–  Aregionofnon-COWanonymousmemory– Mapatagivenaddressusingshmat()

•  CanpersistlongerthananapplicaKon– Mustbeexplicitlydeleted–  Canleakatsystemlevel–  Butclearedaverareboot

33

Page 34: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

SystemVKeysandIDs•  Programmerspickarbitrary32-bitkeys–  UsethesekeystonamesharedabstracKons

•  Findakeyusingshmget(),msgget(),etc.–  Kernelinternallymapskeytoa32-bitID

34

Page 35: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

WindowsComparison•  HardwareexcepKonsaretreatedseparatelyfromIPC–  Upcallstontdll.dll(libcequivalent),tocallhandlers

•  AllIPCtypescanberepresentedashandles–  ProcessterminaKon/suspend/resumesignaledwithprocesshandles

–  SignalscanbeanEventhandle–  SemaphoresandMutexeshavehandles–  Sharedmemoryequallycomplicated(butsKllhandles)

•  Singleselect()-likeAPItowaitonahandletobesignaled

35

Page 36: Signals and Inter-Process Communicaonporter/courses/cse506/s16/slides/ipc.pdf · CSE 506: Operang Systems Windows Comparison • Hardware excepKons are treated separately from IPC

CSE506:Opera.ngSystems

Summary•  Understandsignals•  Understandhigh-levelproperKesofpipesandotherUnixIPCabstracKons–  High-levelcomparisonwithWindows

36