+ All Categories
Home > Documents > CS: Chapter 7 Exceptional Control Flow

CS: Chapter 7 Exceptional Control Flow

Date post: 13-Jan-2016
Category:
Upload: said
View: 29 times
Download: 0 times
Share this document with a friend
Description:
CS: Chapter 7 Exceptional Control Flow. SW Project II: Advanced Linux Programming M ulti- M edia S ystems Engineering Dept. Byoung-Jo CHOI 2007 Fall. - PowerPoint PPT Presentation
Popular Tags:
58
CS: Chapter 7 Exceptional Control Flow SW Project II: SW Project II: Advanced Linux Programming Advanced Linux Programming M ulti- ulti-M edia edia S ystems Engineering Dept. ystems Engineering Dept. Byoung-Jo CHOI Byoung-Jo CHOI 2007 Fall 2007 Fall This lecture material is based on the slides and the textbook, "Computer Systems: A Programmer's Perspective" by R.E.Bryant and D.R.O'Hallaron at Carnegie Melon University.
Transcript
Page 1: CS: Chapter 7 Exceptional Control Flow

CS: Chapter 7Exceptional Control Flow

SW Project II:SW Project II:

Advanced Linux ProgrammingAdvanced Linux ProgrammingMMulti-ulti-MMedia edia SSystems Engineering Dept.ystems Engineering Dept.

Byoung-Jo CHOIByoung-Jo CHOI

2007 Fall2007 Fall

This lecture material is based on the slides and the textbook, "Computer

Systems: A Programmer's Perspective" by R.E.Bryant and D.R.O'Hallaron

at Carnegie Melon University.

Page 2: CS: Chapter 7 Exceptional Control Flow

4 - 2 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

ExceptionsExceptions

ProcessesProcesses

Systems Calls and Error HandlingSystems Calls and Error Handling

Process ControlProcess Control

Chapter Overview

SignalsSignals

Page 3: CS: Chapter 7 Exceptional Control Flow

4 - 3 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Control FlowControl Flow

<startup>inst1

inst2

inst3

…instn

<shutdown>

Computers do Only One ThingComputers do Only One Thing From startup to shutdown, a CPU simply reads and executes

(interprets) a sequence of instructions, one at a time. This sequence is the system’s physical control flow (or flow

of control).

Physical control flow

Time

Page 4: CS: Chapter 7 Exceptional Control Flow

4 - 4 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Altering the Control FlowAltering the Control FlowUp to now: two mechanisms for changing control flow:Up to now: two mechanisms for changing control flow:

Jumps and branches Call and return using the stack discipline.

Both react to changes in program state.

Insufficient for a useful systemInsufficient for a useful system Difficult for the CPU to react to changes in system state.

data arrives from a disk or a network adapter. Instruction divides by zeroUser hits ctl-c at the keyboardSystem timer expires

System needs mechanisms for “exceptional control System needs mechanisms for “exceptional control flow” (ECF)flow” (ECF)

Page 5: CS: Chapter 7 Exceptional Control Flow

4 - 5 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

ECF Exists at All Levels of a SystemECF Exists at All Levels of a SystemExceptionsExceptions

Hardware and operating system kernel code

Concurrent processesConcurrent processes Hardware timer and operating system kernel code

SignalsSignals Operating system kernel code

Non-local jumpsNon-local jumps Application code

Lowerlevels

Higherlevels

Page 6: CS: Chapter 7 Exceptional Control Flow

4 - 6 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

System Context for ExceptionsSystem Context for Exceptions

Local/IO BusLocal/IO Bus

MemoryMemory Networkadapter

Networkadapter

IDE diskcontroller

IDE diskcontroller

Videoadapter

Videoadapter

DisplayDisplay NetworkNetwork

ProcessorProcessor Interruptcontroller

Interruptcontroller

SCSIcontroller

SCSIcontroller

SCSI busSCSI bus

Serial port controllers

Serial port controllers

Parallel portcontroller

Parallel portcontrollerTimerTimer

KeyboardKeyboard MouseMouse PrinterPrinterModemModem

disk

disk CDROM

USB Ports

Super I/O Chip

Page 7: CS: Chapter 7 Exceptional Control Flow

4 - 7 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

ExceptionsExceptions

An An exceptionexception is a transfer of control to the OS in response is a transfer of control to the OS in response to some to some eventevent (i.e., change in processor state) (i.e., change in processor state)

User Process OS

exceptionexception processingby exception handler

exception return (optional)

event currentnext

Page 8: CS: Chapter 7 Exceptional Control Flow

4 - 8 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Interrupt VectorsInterrupt Vectors

Each type of event has a unique exception number k

Index into jump table (a.k.a., interrupt vector)

Jump table entry k points to a function (exception handler).

Handler k is called each time exception k occurs.

interruptvector

01

2 ...n-1

code for exception handler 0

code for exception handler 0

code for exception handler 1

code for exception handler 1

code forexception handler 2

code forexception handler 2

code for exception handler n-1

code for exception handler n-1

...

Exception numbers

Page 9: CS: Chapter 7 Exceptional Control Flow

4 - 9 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Asynchronous Exceptions (Interrupts)Asynchronous Exceptions (Interrupts)

Caused by events external to the processorCaused by events external to the processor Indicated by setting the processor’s interrupt pin handler returns to “next” instruction.

Examples:Examples: I/O interrupts

hitting ctl-c at the keyboardarrival of a packet from a networkarrival of a data sector from a disk

Hard reset interrupthitting the reset button

Soft reset interrupthitting ctl-alt-delete on a PC

Page 10: CS: Chapter 7 Exceptional Control Flow

4 - 10 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Synchronous ExceptionsSynchronous ExceptionsCaused by events that occur as a result of executing an Caused by events that occur as a result of executing an

instruction:instruction: Traps

IntentionalExamples: system calls, breakpoint traps, special instructionsReturns control to “next” instruction

FaultsUnintentional but possibly recoverable Examples: page faults (recoverable), protection faults

(unrecoverable), floating point exceptions.Either re-executes faulting (“current”) instruction or aborts.

Abortsunintentional and unrecoverableExamples: parity error, machine check.Aborts current program

Page 11: CS: Chapter 7 Exceptional Control Flow

4 - 11 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Trap ExampleTrap Example

User Process OS

exceptionOpen file

return

intpop

Opening a FileOpening a File User calls open(filename, options)

Function open executes system call instruction int OS must find or create file, get it ready for reading or writing Returns integer file descriptor

0804d070 <__libc_open>: . . . 804d082: cd 80 int $0x80 804d084: 5b pop %ebx . . .

Page 12: CS: Chapter 7 Exceptional Control Flow

4 - 12 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Fault Example #1Fault Example #1

User Process OS

page faultCreate page and load into memoryreturn

event movl

Memory ReferenceMemory Reference User writes to memory location That portion (page) of user’s memory is currently

on disk

Page handler must load page into physical memory

Returns to faulting instruction Successful on second try

int a[1000];main (){ a[500] = 13;}

80483b7: c7 05 10 9d 04 08 0d movl $0xd,0x8049d10

Page 13: CS: Chapter 7 Exceptional Control Flow

4 - 13 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Fault Example #2Fault Example #2

User Process OS or Hardware

TLB missLook up address translation and store it in a TLB entry

return

event movl

Memory Reference with TLB missMemory Reference with TLB miss User writes to memory location That portion (page) of user’s memory is

currently in physical memory, but the processor has forgotten how to translate this virtual address to the physical address

TLB must be reloaded with current translation

Returns to faulting instruction Successful on second try

int a[1000];main (){ a[500] = 13;}

Page 14: CS: Chapter 7 Exceptional Control Flow

4 - 14 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Fault Example #3Fault Example #3

User Process OS

page fault

Detect invalid address

event movl

Memory ReferenceMemory Reference User writes to memory location Address is not valid

Page handler detects invalid address Sends SIGSEGV signal to user process User process exits with “segmentation fault”

int a[1000];main (){ a[5000] = 13;}

80483b7: c7 05 60 e3 04 08 0d movl $0xd,0x804e360

Send SIGSEGV signal to process

Page 15: CS: Chapter 7 Exceptional Control Flow

4 - 15 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

ProcessesProcessesDefinition: A Definition: A processprocess is an instance of a running program. is an instance of a running program.

One of the most profound ideas in computer science. Not the same as “program” or “processor”

Process provides each program with two key Process provides each program with two key abstractions:abstractions: Logical control flow

Each program seems to have exclusive use of the CPU.

Private address spaceEach program seems to have exclusive use of main memory.

How are these Illusions maintained?How are these Illusions maintained? Process executions interleaved (multitasking) Address spaces managed by virtual memory system

Page 16: CS: Chapter 7 Exceptional Control Flow

4 - 16 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

The World of MultitaskingThe World of MultitaskingSystem Runs Many Processes ConcurrentlySystem Runs Many Processes Concurrently

Process: executing programState consists of memory image + register values + program

counter

Continually switches from one process to anotherSuspend process when it needs I/O resource or timer event

occursResume process when I/O available or given scheduling priority

Appears to user(s) as if all processes executing simultaneously

Even though most systems can only execute one process at a time

Except possibly with lower performance than if running alone

Page 17: CS: Chapter 7 Exceptional Control Flow

4 - 17 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Logical Control FlowsLogical Control Flows

Time

Process A Process B Process C

Each process has its own logical control flow

Page 18: CS: Chapter 7 Exceptional Control Flow

4 - 18 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Concurrent ProcessesConcurrent ProcessesTwo processes Two processes run concurrentlyrun concurrently ( (are concurrent)are concurrent) if if

their flows overlap in time.their flows overlap in time.

Otherwise, they are Otherwise, they are sequential.sequential.

Examples:Examples: Concurrent: A & B, A & C Sequential: B & C

Time

Process A Process B Process C

Page 19: CS: Chapter 7 Exceptional Control Flow

4 - 19 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

User View of Concurrent ProcessesUser View of Concurrent Processes

Control flows for concurrent processes are physically Control flows for concurrent processes are physically disjoint in time.disjoint in time.

However, we can think of concurrent processes are However, we can think of concurrent processes are running in parallel with each other.running in parallel with each other.

Time

Process A Process B Process C

Page 20: CS: Chapter 7 Exceptional Control Flow

4 - 20 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Context SwitchingContext SwitchingProcesses are managed by a shared chunk of OS code Processes are managed by a shared chunk of OS code

called the called the kernelkernel Important: the kernel is not a separate process, but rather

runs as part of some user process

Control flow passes from one process to another via a Control flow passes from one process to another via a context switch.context switch.

Process Acode

Process Bcode

user code

kernel code

user code

kernel code

user code

Timecontext switch

context switch

Page 21: CS: Chapter 7 Exceptional Control Flow

4 - 21 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Private Address SpacesPrivate Address SpacesEach process has its own private address space.Each process has its own private address space.

kernel virtual memory(code, data, heap, stack)

memory mapped region forshared libraries

run-time heap(managed by malloc)

user stack(created at runtime)

unused0

%esp (stack pointer)

memoryinvisible touser code

brk

0xc0000000

0x08048000

0x40000000

read/write segment(.data, .bss)

read-only segment(.init, .text, .rodata)

loaded from the executable file

0xffffffff

Page 22: CS: Chapter 7 Exceptional Control Flow

4 - 22 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

fork: Creating New Processesfork: Creating New Processesint fork(void)int fork(void)

creates a new process (child process) that is identical to the calling process (parent process)

returns 0 to the child process returns child’s pid to the parent process

if (fork() == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}

Fork is interesting(and often confusing)because it is calledonce but returns twice

Page 23: CS: Chapter 7 Exceptional Control Flow

4 - 23 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

fork Example #1fork Example #1

void fork1(){ int x = 1; pid_t pid = fork(); if (pid == 0) {

printf("Child: x=%d\n",++x); } else {

printf("Parent: x=%d\n",--x); } printf("Bye from %d with x = %d\n", getpid(), x);}

Key PointsKey Points Parent and child both run same code

Distinguish parent from child by return value from fork Start with same state, but each has private copy

Including shared output file descriptorRelative ordering of their print statements undefined

Parent:x=0, Bye… x=0

Child:x=2, Bye… x=2

Page 24: CS: Chapter 7 Exceptional Control Flow

4 - 24 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

fork Example #2fork Example #2

void fork2(){ printf("L0\n"); fork(); printf("L1\n"); fork(); printf("Bye\n");}

Key PointsKey Points Both parent and child can continue forking

L0 L1

L1

Bye

Bye

Bye

Bye

Page 25: CS: Chapter 7 Exceptional Control Flow

4 - 25 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

exit: Destroying Processesexit: Destroying Processes

void exit(int status)void exit(int status) exits a process

Normally return with status 0

atexit() registers functions to be executed upon exit

void cleanup(void) { printf("cleaning up\n");}

void fork6() { atexit(cleanup); fork(); exit(0);}

Page 26: CS: Chapter 7 Exceptional Control Flow

4 - 26 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

ZombiesZombiesIdeaIdea

When process terminates, still consumes system resourcesVarious tables maintained by OS

Called a “zombie”Living corpse, half alive and half dead

ReapingReaping Performed by parent by “waiting” on terminated child Parent is given exit status information Kernel discards process

What if Parent Doesn’t Reap?What if Parent Doesn’t Reap? If any parent terminates without reaping a child, then child

will be reaped by init process (parent of all processes) Only need explicit reaping for long-running processes

E.g., shells and servers

Page 27: CS: Chapter 7 Exceptional Control Flow

4 - 27 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Wait: Synchronizing with and Reaping ChildrenWait: Synchronizing with and Reaping Children

int wait(int *child_status)int wait(int *child_status) Suspends current process until one of its children, p,

terminates

Return value is the pid of process p

Returning from wait reaps process p

If child_status != NULL, then the object it points to will be set to a status indicating why process p terminated

Page 28: CS: Chapter 7 Exceptional Control Flow

4 - 28 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Wait ExampleWait Example

void fork9() { int child_status;

if (fork() == 0) { printf("HC: hello from child\n"); } else { printf("HP: hello from parent\n"); wait(&child_status); printf("CT: child has terminated\n"); } printf("Bye\n"); exit();}

HP

HC Bye

CT Bye

Page 29: CS: Chapter 7 Exceptional Control Flow

4 - 29 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

If multiple children completed, will take in arbitrary order Can use macros WIFEXITED and WEXITSTATUS to get

information about exit statusvoid fork10(){ pid_t pid[N]; int i, child_status; for (i = 0; i < N; i++)

if ((pid[i] = fork()) == 0) exit(100+i); /* Child */

for (i = 0; i < N; i++) {pid_t wpid = wait(&child_status);if (WIFEXITED(child_status)) printf("Child %d terminated with exit status %d\n",

wpid, WEXITSTATUS(child_status));else printf("Child %d terminate abnormally\n", wpid);

}}

Waiting for Multiple ChildrenWaiting for Multiple Children

Page 30: CS: Chapter 7 Exceptional Control Flow

4 - 30 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

waitpid: Waiting for a Specific Childwaitpid: Waiting for a Specific Child waitpid(pid, &status, options)

Can wait for specific processVarious options (see CS:APP)

void fork11(){ pid_t pid[N]; int I, child_status; for (i = 0; i < N; i++)

if ((pid[i] = fork()) == 0) exit(100+i); /* Child */

for (i = 0; i < N; i++) {pid_t wpid = waitpid(pid[i], &child_status, 0);if (WIFEXITED(child_status)) printf("Child %d terminated with exit status %d\n",

wpid, WEXITSTATUS(child_status));else printf("Child %d terminated abnormally\n", wpid);

}

Page 31: CS: Chapter 7 Exceptional Control Flow

4 - 31 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

exec: Running New Programsexec: Running New Programsint execl(char *path, char *arg0, char *arg1, …, 0)int execl(char *path, char *arg0, char *arg1, …, 0)

Family of functions wrapped around execv Loads and runs executable at path with args arg0, arg1, …

path is the complete path of an executablearg0 becomes the name of the process

» typically arg0 is either identical to path, or else it contains only the executable filename from path

“real” arguments to the executable start with arg1, etc. list of args is terminated by a (char *)0 argument

Returns -1 if error, otherwise doesn’t return!

main() { if (fork() == 0) { execl("/usr/bin/cp", "cp", "foo", "bar", 0); } wait(NULL); printf("copy completed\n"); exit();}

Page 32: CS: Chapter 7 Exceptional Control Flow

4 - 32 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Exec ExampleExec ExampleTypically used in conjunction with fork.Typically used in conjunction with fork.

main() { if (fork() == 0) { execl("/usr/bin/cp", "cp", "foo", "bar", 0); } wait(NULL); printf("copy completed\n"); exit();}

Page 33: CS: Chapter 7 Exceptional Control Flow

4 - 33 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Summary of Process ControlSummary of Process ControlSpawning ProcessesSpawning Processes

Call to forkOne call, two returns

Terminating ProcessesTerminating Processes Call exit

One call, no return

Reaping ProcessesReaping Processes Call wait or waitpid

Replacing Program Executed by ProcessReplacing Program Executed by Process Call execl (or variant)

One call, (normally) no return

Page 34: CS: Chapter 7 Exceptional Control Flow

4 - 34 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Linux Process HierarchyLinux Process Hierarchy

Login shell

ChildChildChild

GrandchildGrandchild

[0]

Daemone.g. httpd

init [1]

Page 35: CS: Chapter 7 Exceptional Control Flow

4 - 35 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Unix Startup: Step 1Unix Startup: Step 1

init [1]

[0] Process 0: handcrafted kernel process

Child process 1 execs /sbin/init

1. Pushing reset button loads the PC with the address of a small bootstrap program.2. Bootstrap program loads the boot block (disk block 0).3. Boot block program loads kernel binary (e.g., /boot/vmlinux)4. Boot block program passes control to kernel.5. Kernel handcrafts the data structures for process 0.

Process 0 forks child process 1

Page 36: CS: Chapter 7 Exceptional Control Flow

4 - 36 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Unix Startup: Step 2Unix Startup: Step 2

init [1]

[0]

gettyDaemonse.g. ftpd, httpd

/etc/inittabinit forks and execs daemons per /etc/inittab, and forks and execs a getty program for the console

Page 37: CS: Chapter 7 Exceptional Control Flow

4 - 37 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Unix Startup: Step 3Unix Startup: Step 3

init [1]

[0]

The getty process execs a login program

login

Page 38: CS: Chapter 7 Exceptional Control Flow

4 - 38 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Unix Startup: Step 4Unix Startup: Step 4

init [1]

[0]

login reads login-ID and passwd.if OK, it execs a shell.if not OK, it execs another getty

tcsh

In case of login on the consolexinit may be used instead ofa shell to start the window manger

Page 39: CS: Chapter 7 Exceptional Control Flow

4 - 39 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Shell ProgramsShell ProgramsA A shellshell is an application program that runs programs on is an application program that runs programs on

behalf of the user.behalf of the user. sh – Original Unix Bourne Shell csh – BSD Unix C Shell, tcsh – Enhanced C Shell bash –Bourne-Again Shell (Linux version of sh)int main() { char cmdline[MAXLINE];

while (1) {/* read */printf("> "); Fgets(cmdline, MAXLINE, stdin); if (feof(stdin)) exit(0);

/* evaluate */eval(cmdline);

} }

Execution is a sequence of Execution is a sequence of read/evaluate stepsread/evaluate steps

Page 40: CS: Chapter 7 Exceptional Control Flow

4 - 40 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Simple Shell eval FunctionSimple Shell eval Functionvoid eval(char *cmdline) { char *argv[MAXARGS]; /* argv for execve() */ int bg; /* should the job run in bg or fg? */ pid_t pid; /* process id */

bg = parseline(cmdline, argv); if (!builtin_command(argv)) {

if ((pid = Fork()) == 0) { /* child runs user job */ if (execve(argv[0], argv, environ) < 0) {

printf("%s: Command not found.\n", argv[0]);exit(0);

}}

if (!bg) { /* parent waits for fg job to terminate */ int status;

if (waitpid(pid, &status, 0) < 0)unix_error("waitfg: waitpid error");

}else /* otherwise, don’t wait for bg job */ printf("%d %s", pid, cmdline);

}}

Page 41: CS: Chapter 7 Exceptional Control Flow

4 - 41 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Problem with Simple Shell ExampleProblem with Simple Shell ExampleShell correctly waits for and reaps foreground jobs.Shell correctly waits for and reaps foreground jobs.

But what about background jobs?But what about background jobs? Will become zombies when they terminate. Will never be reaped because shell (typically) will not

terminate. Creates a memory leak that will eventually crash the kernel

when it runs out of memory.

Solution: Reaping background jobs requires a Solution: Reaping background jobs requires a mechanism called a mechanism called a signalsignal..

Page 42: CS: Chapter 7 Exceptional Control Flow

4 - 42 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

SignalsSignalsA A signalsignal is a small message that notifies a process that is a small message that notifies a process that

an event of some type has occurred in the system.an event of some type has occurred in the system. Kernel abstraction for exceptions and interrupts. Sent from the kernel (sometimes at the request of another

process) to a process. Different signals are identified by small integer ID’s (1-30) The only information in a signal is its ID and the fact that it

arrived.

IDID NameName Default ActionDefault Action Corresponding EventCorresponding Event

22 SIGINTSIGINT TerminateTerminate Interrupt from keyboard (Interrupt from keyboard (ctl-cctl-c))

99 SIGKILLSIGKILL TerminateTerminate Kill program (cannot override or ignore)Kill program (cannot override or ignore)

1111 SIGSEGVSIGSEGV Terminate & DumpTerminate & Dump Segmentation violationSegmentation violation

1414 SIGALRMSIGALRM TerminateTerminate Timer signalTimer signal

1717 SIGCHLDSIGCHLD IgnoreIgnore Child stopped or terminatedChild stopped or terminated

man 7 signal

Page 43: CS: Chapter 7 Exceptional Control Flow

4 - 43 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Signal Concepts Signal Concepts Sending a signalSending a signal

Kernel sends (delivers) a signal to a destination process by updating some state in the context of the destination process.

Kernel sends a signal for one of the following reasons:Kernel has detected a system event such as divide-by-zero

(SIGFPE) or the termination of a child process (SIGCHLD)Another process has invoked the kill system call to explicitly

request the kernel to send a signal to the destination process.

Page 44: CS: Chapter 7 Exceptional Control Flow

4 - 44 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Signal Concepts (continued)Signal Concepts (continued)Receiving a signalReceiving a signal

A destination process receives a signal when it is forced by the kernel to react in some way to the delivery of the signal.

Three possible ways to react: Ignore the signal (do nothing)Terminate the process (with optional core dump).Catch the signal by executing a user-level function called a

signal handler.

» Akin to a hardware exception handler being called in response to an asynchronous interrupt.

Page 45: CS: Chapter 7 Exceptional Control Flow

4 - 45 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Signal Concepts (continued)Signal Concepts (continued)A signal is A signal is pendingpending if it has been sent but not yet if it has been sent but not yet

received.received. There can be at most one pending signal of any particular

type. Important: Signals are not queued

If a process has a pending signal of type k, then subsequent signals of type k that are sent to that process are discarded.

A process can A process can blockblock the receipt of certain signals. the receipt of certain signals. Blocked signals can be delivered, but will not be received until

the signal is unblocked.

A pending signal is received at most once.A pending signal is received at most once.

Page 46: CS: Chapter 7 Exceptional Control Flow

4 - 46 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Signal ConceptsSignal ConceptsKernel maintains Kernel maintains pendingpending and and blockedblocked bit vectors in bit vectors in

the context of each process.the context of each process. pending – represents the set of pending signals

Kernel sets bit k in pending whenever a signal of type k is delivered.

Kernel clears bit k in pending whenever a signal of type k is received

blocked – represents the set of blocked signalsCan be set and cleared by the application using the sigprocmask function.

Page 47: CS: Chapter 7 Exceptional Control Flow

4 - 47 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Process GroupsProcess GroupsEvery process belongs to exactly Every process belongs to exactly

one process groupone process group

Fore-ground

job

Back-groundjob #1

Back-groundjob #2

Shell

Child Child

pid=10pgid=10

Foregroundprocess group 20

Backgroundprocess group 32

Backgroundprocess group 40

pid=20pgid=20

pid=32pgid=32

pid=40pgid=40

pid=21pgid=20

pid=22pgid=20

getpgrp() getpgrp() – Return process – Return process group of current processgroup of current process

setpgid() – setpgid() – Change process Change process group of a processgroup of a process

Page 48: CS: Chapter 7 Exceptional Control Flow

4 - 48 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Sending Signals with kill ProgramSending Signals with kill Programkill kill program sends program sends

arbitrary signal to a arbitrary signal to a process or process process or process groupgroup

ExamplesExamples kill –9 24818

Send SIGKILL to process 24818

kill –9 –24817Send SIGKILL to every process in process group 24817.

linux> ./forks 16 linux> Child1: pid=24818 pgrp=24817 Child2: pid=24819 pgrp=24817 linux> ps PID TTY TIME CMD 24788 pts/2 00:00:00 tcsh 24818 pts/2 00:00:02 forks 24819 pts/2 00:00:02 forks 24820 pts/2 00:00:00 ps linux> kill -9 -24817 linux> ps PID TTY TIME CMD 24788 pts/2 00:00:00 tcsh 24823 pts/2 00:00:00 ps linux>

Page 49: CS: Chapter 7 Exceptional Control Flow

4 - 49 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Sending Signals from the KeyboardSending Signals from the KeyboardTyping ctrl-c (ctrl-z) sends a SIGINT (SIGTSTP) to every job in the Typing ctrl-c (ctrl-z) sends a SIGINT (SIGTSTP) to every job in the

foreground process group.foreground process group. SIGINT – default action is to terminate each process SIGTSTP – default action is to stop (suspend) each process

Fore-ground

job

Back-groundjob #1

Back-groundjob #2

Shell

Child Child

pid=10pgid=10

Foregroundprocess group 20

Backgroundprocess group 32

Backgroundprocess group 40

pid=20pgid=20

pid=32pgid=32

pid=40pgid=40

pid=21pgid=20

pid=22pgid=20

Page 50: CS: Chapter 7 Exceptional Control Flow

4 - 50 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Sending Signals with kill FunctionSending Signals with kill Functionvoid fork12(){ pid_t pid[N]; int i, child_status; for (i = 0; i < N; i++)

if ((pid[i] = fork()) == 0) while(1); /* Child infinite loop */

/* Parent terminates the child processes */ for (i = 0; i < N; i++) {

printf("Killing process %d\n", pid[i]);kill(pid[i], SIGINT);

}

/* Parent reaps terminated children */ for (i = 0; i < N; i++) {

pid_t wpid = wait(&child_status);if (WIFEXITED(child_status)) printf("Child %d terminated with exit status %d\n",

wpid, WEXITSTATUS(child_status));else printf("Child %d terminated abnormally\n", wpid);

}}

Page 51: CS: Chapter 7 Exceptional Control Flow

4 - 51 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Receiving SignalsReceiving SignalsSuppose kernel is returning from an exception handler Suppose kernel is returning from an exception handler

and is ready to pass control to process and is ready to pass control to process pp..

Kernel computesKernel computes pnb = pending & ~blocked pnb = pending & ~blocked The set of pending nonblocked signals for process p

If (If (pnb == 0pnb == 0) ) Pass control to next instruction in the logical flow for p.

ElseElse Choose least nonzero bit k in pnb and force process p to

receive signal k. The receipt of the signal triggers some action by p Repeat for all nonzero k in pnb. Pass control to next instruction in logical flow for p.

Page 52: CS: Chapter 7 Exceptional Control Flow

4 - 52 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Default ActionsDefault ActionsEach signal type has a predefined Each signal type has a predefined default actiondefault action, which , which

is one of:is one of: The process terminates The process terminates and dumps core. The process stops until restarted by a SIGCONT signal. The process ignores the signal.

Page 53: CS: Chapter 7 Exceptional Control Flow

4 - 53 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Installing Signal HandlersInstalling Signal HandlersThe The signalsignal function modifies the default action function modifies the default action

associated with the receipt of signal associated with the receipt of signal signumsignum:: handler_t *signal(int signum, handler_t *handler)

Different values for Different values for handlerhandler:: SIG_IGN: ignore signals of type signum SIG_DFL: revert to the default action on receipt of signals of

type signum. Otherwise, handler is the address of a signal handler

Called when process receives signal of type signumReferred to as “installing” the handler.Executing handler is called “catching” or “handling” the signal.When the handler executes its return statement, control passes

back to instruction in the control flow of the process that was interrupted by receipt of the signal.

Page 54: CS: Chapter 7 Exceptional Control Flow

4 - 54 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Signal Handling ExampleSignal Handling Examplevoid int_handler(int sig){ printf("Process %d received signal %d\n", getpid(), sig); exit(0);}

void fork13(){ pid_t pid[N]; int i, child_status; signal(SIGINT, int_handler);

. . .}

linux> ./forks 13 Killing process 24973 Killing process 24974 Killing process 24975 Killing process 24976 Killing process 24977 Process 24977 received signal 2 Child 24977 terminated with exit status 0 Process 24976 received signal 2 Child 24976 terminated with exit status 0 Process 24975 received signal 2 Child 24975 terminated with exit status 0 Process 24974 received signal 2 Child 24974 terminated with exit status 0 Process 24973 received signal 2 Child 24973 terminated with exit status 0 linux>

Page 55: CS: Chapter 7 Exceptional Control Flow

4 - 55 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

Signal Handler FunkinessSignal Handler FunkinessPending signals are not queuedPending signals are not queued

For each signal type, just have single bit indicating whether or not signal is pending

Must check for all terminated jobsMust check for all terminated jobs Typically loop with wait

void child_handler2(int sig){ int child_status; pid_t pid; while ((pid = waitpid(-1, &child_status, WNOHANG)) > 0) {

ccount--;printf("Received signal %d from process %d\n", sig, pid);

}}

void fork15() { signal(SIGCHLD, child_handler2);}

Page 56: CS: Chapter 7 Exceptional Control Flow

4 - 56 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

A Program That Reacts toExternally Generated Events (ctrl-c)A Program That Reacts toExternally Generated Events (ctrl-c)

#include <stdlib.h> #include <stdio.h> #include <signal.h>

void handler(int sig) { printf("You think hitting ctrl-c will stop the bomb?\n"); sleep(2); printf("Well..."); fflush(stdout); sleep(1); printf("OK\n"); exit(0); } main() { signal(SIGINT, handler); /* installs ctl-c handler */ while(1) { } }

Page 57: CS: Chapter 7 Exceptional Control Flow

4 - 57 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

A Program That Reacts to Internally Generated EventsA Program That Reacts to Internally Generated Events#include <stdio.h> #include <signal.h> int beeps = 0; /* SIGALRM handler */void handler(int sig) { printf("BEEP\n"); fflush(stdout); if (++beeps < 5) alarm(1); else { printf("BOOM!\n"); exit(0); } }

main() { signal(SIGALRM, handler); alarm(1); /* send SIGALRM in 1 second */ while (1) { /* handler returns here */ } }

linux> a.out BEEP BEEP BEEP BEEP BEEP BOOM! bass>

Page 58: CS: Chapter 7 Exceptional Control Flow

4 - 58 Multi-Media Systems Engineering Dept.Univ. of IncheonUniv. of Incheon

SummarySummary

Signals provide process-level exception handlingSignals provide process-level exception handling Can generate from user programs Can define effect by declaring signal handler

Some caveatsSome caveats Very high overhead

>10,000 clock cyclesOnly use for exceptional conditions

Don’t have queuesJust one bit for each pending signal type

Nonlocal jumps provide exceptional control flow within Nonlocal jumps provide exceptional control flow within process (See CS:APP)process (See CS:APP) Within constraints of stack discipline


Recommended