15 213 The course that gives CMU its
- Slides: 34
15 -213 “The course that gives CMU its Zip!” Exceptional Control Flow & Processes October 2, 2008 Topics n n n lecture-11. ppt Exceptions Processes and context switches Creating and destroying processes
Control Flow Processors do only one thing: n n From startup to shutdown, a CPU simply reads and executes (interprets) a sequence of instructions, one at a time This sequence is the CPU’s control flow (or flow of control) Physical control flow Time – 2– <startup> inst 1 inst 2 inst 3 … instn <shutdown> 15 -213, F’ 08
Altering the Control Flow Up to now: two mechanisms for changing control flow: n Jumps and branches Call and return Both react to changes in program state n Insufficient for a useful system n Difficult for the CPU to react to changes in system state l data arrives from a disk or a network adapter l instruction divides by zero l user hits Ctrl-C at the keyboard l System timer expires System needs mechanisms for “exceptional control flow” – 3– 15 -213, F’ 08
Exceptional Control Flow n Mechanisms for exceptional control flow exists at all levels of a computer system. Low level Mechanism n exceptions l change in control flow in response to a system event (i. e. , change in system state) n combination of hardware and OS software Higher Level Mechanisms n n Process context switch Signals Nonlocal jumps: setjmp()/longjmp() implemented by either: l OS software (context switch and signals) l C language runtime library: nonlocal jumps – 4– 15 -213, F’ 08
Exceptions An exception is a transfer of control to the OS in response to some event (i. e. , change in processor state) User Process event current next OS exception processing by exception handler exception return (optional) – 5– 15 -213, F’ 08
Interrupt Vectors Exception numbers interrupt vector 0 1 2 n-1 . . . n code for exception handler 0 Each type of event has a unique exception number k n code for exception handler 1 n code for exception handler 2 n Index into jump table (a. k. a. , interrupt vector) Entry k points to a function (exception handler) Handler k is called each time exception k occurs . . . code for exception handler n-1 – 6– 15 -213, F’ 08
Asynchronous Exceptions (Interrupts) Caused by events external to the processor n Indicated by setting the processor’s interrupt pin n handler returns to “next” instruction Examples: n I/O interrupts l hitting Ctrl-C at the keyboard l arrival of a packet from a network l arrival of data from a disk n Hard reset interrupt l hitting the reset button n Soft reset interrupt l hitting Ctrl-Alt-Delete on a PC – 7– 15 -213, F’ 08
Synchronous Exceptions Caused by events that occur as a result of executing an instruction: n Traps l Intentional l Examples: system calls, breakpoint traps, special instructions l Returns control to “next” instruction n Faults l Unintentional but possibly recoverable l Examples: page faults (recoverable), protection faults (unrecoverable), floating point exceptions l Either re-executes faulting (“current”) instruction or aborts n Aborts l unintentional and unrecoverable l Examples: parity error, machine check l Aborts current program – 8– 15 -213, F’ 08
Trap Example Opening a File n User calls open(filename, options) 0804 d 070 <__libc_open>: . . . 804 d 082: cd 80 804 d 084: 5 b. . . int pop $0 x 80 %ebx l Function open executes system call instruction int n OS must find or create file, get it ready for reading or writing n Returns integer file descriptor User Process int pop – 9– OS exception Open file return 15 -213, F’ 08
Fault Example #1 Memory Reference n User writes to memory location n That portion (page) of user’s memory is currently on disk 80483 b 7: n n n c 7 05 10 9 d 04 08 0 d movl OS page fault return – 10 – $0 xd, 0 x 8049 d 10 Page handler must load page into physical memory Returns to faulting instruction Successful on second try User Process event movl int a[1000]; main () { a[500] = 13; } Create page and load into memory 15 -213, F’ 08
Fault Example #2 int a[1000]; main () { a[5000] = 13; } Invalid Memory Reference n User writes to memory location n Address is not valid 80483 b 7: c 7 05 60 e 3 04 08 0 d $0 xd, 0 x 804 e 360 n Page handler detects invalid address Sends SIGSEGV signal to user process n User process exits with “segmentation fault” n User Process event movl OS page fault Detect invalid address Signal process – 11 – 15 -213, F’ 08
Processes Definition: A process is an instance of a running program. n One of the most profound ideas in computer science. n Not the same as “program” or “processor” Process provides each program with two key abstractions: n Logical control flow l Each program seems to have exclusive use of the CPU. n Private address space l Each program seems to have exclusive use of main memory. How are these Illusions maintained? n n Process executions interleaved (multitasking) Address spaces managed by virtual memory system l (we’ll talk about this in a couple of weeks) – 12 – 15 -213, F’ 08
Logical Control Flows Each process has its own logical control flow – 13 – 15 -213, F’ 08
Concurrent Processes Two processes run concurrently (are concurrent) if their flows overlap in time Otherwise, they are sequential Examples: n n Concurrent: A & B, A & C Sequential: B & C Process A Process B Process C Time – 14 – 15 -213, F’ 08
User View of Concurrent Processes Control flows for concurrent processes are physically disjoint in time. However, we can think of concurrent processes are running in parallel with each other. Process A Process B Process C Time – 15 -213, F’ 08
Context Switching Processes are managed by a shared chunk of OS code called the kernel n 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 context switch. Process A code Process B code user code Time kernel code context switch user code – 16 – 15 -213, F’ 08
fork: Creating New Processes int fork(void) n n n 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 childn"); } else { printf("hello from parentn"); } – 17 – Fork is interesting (and often confusing) because it is called once but returns twice 15 -213, F’ 08
Fork Example #1 Key Points n Parent and child both run same code l Distinguish parent from child by return value from fork n Start with same state, but each has private copy l Including shared output file descriptor l Relative ordering of their print statements undefined void fork 1() { int x = 1; pid_t pid = fork(); if (pid == 0) { printf("Child has x = %dn", ++x); } else { printf("Parent has x = %dn", --x); } printf("Bye from process %d with x = %dn", getpid(), x); } – 18 – 15 -213, F’ 08
Fork Example #2 Key Points n Both parent and child can continue forking void fork 2() { printf("L 0n"); fork(); printf("L 1n"); fork(); printf("Byen"); } – 19 – L 0 L 1 Bye Bye 15 -213, F’ 08
Fork Example #3 Key Points n Both parent and child can continue forking void fork 3() { printf("L 0n"); fork(); printf("L 1n"); fork(); printf("L 2n"); fork(); printf("Byen"); } L 1 L 0 – 20 – L 1 L 2 Bye Bye 15 -213, F’ 08
Fork Example #4 Key Points n Both parent and child can continue forking void fork 4() { printf("L 0n"); if (fork() != 0) { printf("L 1n"); if (fork() != 0) { printf("L 2n"); fork(); } } printf("Byen"); } – 21 – Bye L 0 L 1 L 2 Bye 15 -213, F’ 08
Fork Example #5 Key Points n Both parent and child can continue forking void fork 5() { printf("L 0n"); if (fork() == 0) { printf("L 1n"); if (fork() == 0) { printf("L 2n"); fork(); } } printf("Byen"); } – 22 – Bye L 2 L 1 L 0 Bye Bye 15 -213, F’ 08
exit: Ending a process void exit(int status) n exits a process l Normally return with status 0 n atexit() registers functions to be executed upon exit void cleanup(void) { printf("cleaning upn"); } void fork 6() { atexit(cleanup); fork(); exit(0); } – 23 – 15 -213, F’ 08
Zombies Idea n When process terminates, still consumes system resources l Various tables maintained by OS n Called a “zombie” l Living corpse, half alive and half dead Reaping n n n Performed by parent on terminated child Parent is given exit status information Kernel discards process What if Parent Doesn’t Reap? n if any parent terminates without reaping a child, then child will be reaped by init process n so, only need explicit reaping in long-running processes l e. g. , shells and servers – 24 – 15 -213, F’ 08
Zombie Example void fork 7() { if (fork() == 0) { /* Child */ printf("Terminating Child, PID = %dn", getpid()); exit(0); } else { printf("Running Parent, PID = %dn", getpid()); linux>. /forks 7 & while (1) [1] 6639 ; /* Infinite loop */ Running Parent, PID = 6639 } Terminating Child, PID = 6640 } linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6639 ttyp 9 00: 03 6640 ttyp 9 00: 00 6641 ttyp 9 00: 00 linux> kill 6639 [1] Terminated linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6642 ttyp 9 00: 00 – 25 – CMD tcsh forks <defunct> ps n ps shows child process as “defunct” n Killing parent allows child to be reaped by tcsh CMD tcsh ps 15 -213, F’ 08
Nonterminating Child Example void fork 8() { if (fork() == 0) { /* Child */ printf("Running Child, PID = %dn", getpid()); while (1) ; /* Infinite loop */ } else { printf("Terminating Parent, PID = %dn", getpid()); linux>. /forks 8 exit(0); Terminating Parent, PID = 6675 } } Running Child, PID = 6676 linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6676 ttyp 9 00: 06 6677 ttyp 9 00: 00 linux> kill 6676 linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6678 ttyp 9 00: 00 – 26 – CMD tcsh forks ps CMD tcsh ps n n Child process still active even though parent has terminated Must kill explicitly, or else will keep running indefinitely 15 -213, F’ 08
wait: Synchronizing with Children int wait(int *child_status) n n n – 27 – suspends current process until one of its children terminates return value is the pid of the child process that terminated if child_status != NULL, then the object it points to will be set to a status indicating why the child process terminated 15 -213, F’ 08
wait: Synchronizing with Children void fork 9() { int child_status; if (fork() == 0) { printf("HC: hello from childn"); } else { printf("HP: hello from parentn"); wait(&child_status); printf("CT: child has terminatedn"); } printf("Byen"); exit(); } – 28 – HC Bye HP CT Bye 15 -213, F’ 08
wait() Example n n If multiple children completed, will take in arbitrary order Can use macros WIFEXITED and WEXITSTATUS to get information about exit status void fork 10() { pid_t pid[N]; int i; int 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 %dn", wpid, WEXITSTATUS(child_status)); else printf("Child %d terminate abnormallyn", wpid); 15 -213, F’ 08 – 29 – } }
waitpid(): Waiting for a Specific Process n waitpid(pid, &status, options) l suspends current process until specific process terminates l various options (that we won’t talk about) void fork 11() { pid_t pid[N]; int i; int 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 %dn", wpid, WEXITSTATUS(child_status)); else printf("Child %d terminated abnormallyn", wpid); } – 30 – 15 -213, F’ 08
exec: Loading and Running Programs int execl(char *path, char *arg 0, char *arg 1, …, 0) n Loads and runs executable at path with args arg 0, arg 1, … l path is the complete path of an executable object file l By convention, arg 0 is the name of the executable object file l “Real” arguments to the program start with arg 1, etc. l List of args is terminated by a (char *)0 argument l Environment taken from char **environ, which points to an array of “name=value” strings: » USER=ganger » LOGNAME=ganger » HOME=/afs/cs. cmu. edu/user/ganger – 31 – n Returns -1 if error, otherwise doesn’t return! n Family of functions includes execv, execve (base function), execvp, execle, and execlp 15 -213, F’ 08
exec: Loading and Running Programs main() { if (fork() == 0) { execl("/usr/bin/cp", "foo", "bar", 0); } wait(NULL); printf("copy completedn"); exit(); } – 32 – 15 -213, F’ 08
Summarizing Exceptions n Events that require nonstandard control flow n Generated externally (interrupts) or internally (traps and faults) Processes n n n – 33 – At any given time, system has multiple active processes Only one can execute at a time, though Each process appears to have total control of processor + private memory space 15 -213, F’ 08
Summarizing (cont. ) Spawning Processes n Call to fork l One call, two returns Process completion n Call exit l One call, no return Reaping and Waiting for Processes n Call wait or waitpid Loading and Running Programs n Call execl (or variant) l One call, (normally) no return – 34 – 15 -213, F’ 08
- Cmu 15-213
- Cmu 15 213
- 18-213 cmu
- 18-213 cmu
- Cmu 15-213
- 18 213
- 18-213 cmu
- Cmu 15-213
- Chiến lược kinh doanh quốc tế của walmart
- Sau thất bại ở hồ điển triệt
- Block nhĩ thất cao độ
- Tìm vết của đường thẳng
- Thể thơ truyền thống
- Tôn thất thuyết là ai
- Hãy nói thật ít để làm được nhiều
- Thơ thất ngôn tứ tuyệt đường luật
- Gây tê cơ vuông thắt lưng
- Phân độ lown
- Cmu machine learning
- The skeleton gives the body its basic shape
- Course number and title
- Course interne course externe
- What is half brick wall
- Ct 213
- Sbi 213
- Outline 213
- Ct-213
- 15 213
- Significant figures table
- Ct 213
- Ee 213
- 213 table
- Cs213 northwestern
- Outline 213
- Poli 213