Exceptional Control Flow Part II

Slides:



Advertisements
Similar presentations
Recitation 8 (Nov. 1) Outline Process & job control Lab 5 Reminder Lab 5: Due Thursday Minglong Shao Office hours: Thursdays 5-6PM.
Advertisements

Recitation 8: 10/28/02 Outline Processes Signals –Racing Hazard –Reaping Children Annie Luo Office Hours: Thursday 6:00.
1 CS345 Operating Systems Φροντιστήριο Άσκησης 1.
Exceptional Control Flow Processes Today. Control Flow Processors do only one thing: From startup to shutdown, a CPU simply reads and executes (interprets)
CS283 Systems Programming Process Management and Signals
Fabián E. Bustamante, Spring 2007 Exceptional Control Flow II Today Process Hierarchy Shells Signals Nonlocal jumps Next time Virtual memory.
Carnegie Mellon Introduction to Computer Systems /18-243, spring th Lecture, Mar. 5 th Instructors: Gregory Kesden and Markus Püschel.
15-213, Fall 06 Outline Shell Lab Processes Signals.
Carnegie Mellon 1 Exceptional Control Flow: Signals and Nonlocal Jumps : Introduction to Computer Systems 13 th Lecture, Oct. 7, 2010 Instructors:
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
Processes CSCI 444/544 Operating Systems Fall 2008.
Exceptional Control Flow Part II Oct. 22, 2002 Topics Process Hierarchy Shells Signals Nonlocal jumps class17.ppt “The course that gives CMU its.
Slide 6-1 Copyright © 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6 Threads and Scheduling 6.
CSSE Operating Systems
Section A (March 14) Outline Exceptions Process Signals Non-local jumps Reminders Lab4: Due Next Thursday TA: Kun Gao Shamelessly Modified from Minglong.
Processes, Signals, I/O, Shell lab
Exceptional Control Flow Part II Topics Process Hierarchy Signals CS213.
UNIX Signals Bach 7.2 Operating Systems Course The Hebrew University Spring 2010.
Exceptional Control Flow Topics Exceptions Process hierarchy Shells Signals CS 105 “Tour of the Black Holes of Computing”
CS 201 Exceptions and System calls Part II. – 2 – Shell Programs A shell is an application program that runs programs on behalf of the user. sh – Original.
Exec Function calls Used to begin a processes execution. Accomplished by overwriting process imaged of caller with that of called. Several flavors, use.
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
Agenda  Working with Processes: Purpose Running Programs within same process (execl, execlp, execle, execv, execvp, execve) “Spawning” other process (fork,
System calls for Process management
Program Translation and Execution II: Processes Oct 1, 1998 Topics User-level view of processes Implementation of processes setjmp/longjmp class12.ppt.
Concurrent Processes Processes can concurrently run same program. Processes can concurrently run same program. Processes can start other processes. Processes.
Operating Systems Process Creation
What is a Process? u A process is an executable “cradle” in which a program may run u This “cradle” provides an environment in which the program can run,
Outline for Today Objectives –Finish discussion of Birrell –UNIX Signals –Eraser Administrative –Spider talk after class.
1 Signals (continued) CS 241 April 9, 2012 University of Illinois.
UNIX Signals * POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm * Interval Timers * POSIX.1b Timers *
Exceptional Control Flow Part II Topics Process Hierarchy Shells Signals.
Operating Systems Recitation 4, April th, 2002 Signals.
Exceptional Control Flow
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
1 Exceptional Control Flow III. 2 Outline Loading and Running Programs Multitasking, shells Suggested reading 8.4.
System calls for Process management Process creation, termination, waiting.
1 Lecture 19: Unix signals and Terminal management n what is a signal n signal handling u kernel u user n signal generation n signal example usage n terminal.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Signals.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
Exceptional Control Flow II Oct 23, 2001 Topics Exceptions Process context switches class17.ppt “The course that gives CMU its Zip!”
Process Manipulation. Process Manipulation in UNIX Basic process manipulation: creation, program loading, exiting, … fork(), exec(), wait(), exit() Process.
Recitation 7 – 3/18/02 Outline fork and scheduling Signals
G.Jyostna.
Recitation 7 (Oct. 25) Outline Minglong Shao Office hours: Reminders
CS 3214 Introduction to Computer Systems
Section 8: Processes What is a process Creating processes Fork-Exec
Unix Process Management
Processes in Unix, Linux, and Windows
Exceptional Control Flow Part II
Signals Adapted from slides of Gregory Kesden and Markus Püschel of Carnegie Mellon Univ.
Exceptional Control Flow
Instructors: Randy Bryant, Dave O’Hallaron, and Greg Kesden
Exceptional Control Flow
Exceptional Control Flow Part II
Processes in Unix, Linux, and Windows
Exceptional Control Flow
Processes in Unix, Linux, and Windows
Exceptional Control Flow
Processes Prof. Ikjun Yeom TA – Mugyo
Exceptional Control Flow
CS 105 “Tour of the Black Holes of Computing!”
CS 105 “Tour of the Black Holes of Computing!”
Exceptional Control Flow
CSE 451: Operating Systems Winter 2003 Lecture 4 Processes
Processes in Unix, Linux, and Windows
Processes in Unix and Windows
Exceptional Control Flow
Exceptional Control Flow
Presentation transcript:

Exceptional Control Flow Part II Topics Exec calls Shells Signals Nonlocal jumps

Argument Lists Given the following definition of main: int main(int argc, char *argv[ ]); Parameter argv is a pointer to an array of argc items. If this main for “ls”, then the following diagram shows ls –lt /usr/include argv[] argv argv[0] "ls" argv[1] "-lt" argv[2] argc = 3 NULL "/usr/include"

Environment Lists Given the following definition of main: int main(int argc, char *argv[ ], char *envp[ ]); Parameter envp is a pointer to an array of environment variables. envp[] envp envp[0] "PWD=/usr/droh" envp[1] "PRINTER=iron" ... envp[n-1] NULL "USER=droh"

Stack Organization ... ... Bottom of stack Null-terminated 0xbfffffff Bottom of stack Null-terminated environment variable strings Null-terminated command-line arg strings (Unused) envp[n] == NULL envp[n-1] ... envp[0] environ argv[argc] = NULL argv[argc-1] ... argv[0] (Dynamic linker variables) envp argv argc main(argc,argv,envp) 0xbffffa7c Stack frame for main Top of stack

Demo ch08/env

exec: Running new programs int execl(char *path, char *arg0, char *arg1, …, 0) loads and runs executable at path with args arg0, arg1, … path is the complete path of an executable arg0 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", “file1", “file2", 0); } wait(NULL); printf("copy completed\n"); exit();

Demo ch08/exec

exec: Many Flavors There are six different exec calls. They can be distinguished by their suffixes. “l”, for list form: arg0, arg1, ..., 0 “v”, for vector form: argv[ ] “e”, for passing the environment as envp[ ]. Non-e functions can call getenv, or use the environ variable. “p”, uses the PATH environment variable to find filename. execl(pathname, arg0, arg1, ..., 0) execv(pathname, argv[]) execle(pathname, arg0, arg1, ..., 0, envp[]) execve(pathname, argv[], envp[]) execlp(filename, arg0, arg1, ..., 0) execvp(filename, argv[])

Multitasking and Shells

Multitasking System Runs Many Processes Concurrently Process: executing program State consists of memory contents and register values, including EIP and EFLAGS Continually switches from one process to another Suspend process when it needs I/O resource or timer event occurs Resume process when I/O available or given scheduling priority Appears to users as if all processes executing simultaneously Even though most systems can only execute one process at a time Lower performance than if running alone

Programmer’s Model of Multitasking Basic Functions fork() spawns new process Called once, returns twice exit() terminates own process Called once, never returns Puts it into “zombie” status wait() and waitpid() wait for and reap terminated children execl() and execve() run a new program in an existing process Called once, (normally) never returns

Writing a Shell A shell is an application program that runs programs on behalf of the user. sh – Original Unix Bourne Shell csh – BSD Unix C Shell, tcsh – Enhanced C Shell bash – Bourne-Again Shell With fork and exec we can build a primitive shell. Read a command Parse command and convert parameters to argv[ ] array Fork to create child process Child process calls exec, passes argv[ ] to start program If foreground process, parent waits for child to finish

Demo, ch08/shell

Problem with Simple Shell Example Shell correctly waits for and reaps foreground 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 mechanism called a signal.

Signals

Signals A signal is a small message that notifies a process that 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 The only information in a signal is its ID and the fact that it arrived. ID Name Default Action Corresponding Event 2 SIGINT Terminate Interrupt from keyboard (ctl-c) 9 SIGKILL Kill program (cannot override or ignore) 11 SIGSEGV Terminate & Dump Segmentation violation 14 SIGALRM Timer signal 15 SIGTERM Kill program (software signal) 17 SIGCHLD Ignore Child stopped or terminated 30 SIGUSR1 User defined

Signal Concepts List of Signals Sending a signal /usr/include/sys/signal.h (32 signals) Sending 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.

Signal Concepts Receiving 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. 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.

Signal Concepts A signal is pending if it has been sent but not yet 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 block 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.

Signal Concepts Kernel maintains pending and blocked bit vectors in the context of each process. SigPnd – 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 No queue! SigBlk – set of blocked signals kernel blocks before calling handler, unblocks when done application can change with sigprocmask function. Demo (jupiter) /proc/uptime (uptime) /proc/cpuinfo (dmesg – L1, L2 cache size) /proc/*/status (view files)

Receiving Signals When the kernel is ready to pass control to process p... It computes pnb = pending & ~blocked The set of pending nonblocked signals for process p If (pnb) Choose least significant 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. else Pass control to next instruction in the logical flow for p.

Default Actions (p. 618) Each signal type has a predefined default action, which is one of: The process terminates SIGINT (Ctrl-C), SIGKILL (kill program) The process terminates and dumps core SIGFPE (floating point exception), SIGABORT (abort function) The process stops until restarted SIGTSTP/SIGCONT (Ctrl-S, Ctrl-Q) The process ignores the signal

Installing Signal Handlers The signal function modifies the default action associated with the receipt of signal signum: handler_t *signal(int signum, handler_t *handler) Different values for handler: 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 signum Referred 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.

Process Groups Every process belongs to exactly one process group. By default, child inherits process group of parent. Shell pid=10 pgid=10 Fore- ground job Back- ground job #1 Back- ground job #2 pid=20 pgid=20 pid=32 pgid=32 pid=40 pgid=40 Background process group 32 Background process group 40 Child Child getpgrp() – Return process group of current process setpgid() – Change process group of a process pid=21 pgid=20 pid=22 pgid=20 Foreground process group 20

Sending Signals with kill Command The kill command sends any signal to a process or process group. Examples kill –l (list signals) kill –9 24818 Send SIGKILL to process 24818 kill –9 –24817 Send SIGKILL to every process in process group 24817. Demo ch08/sig/killsig 1-5 ch08/sig/forks 12-13

Signal Handler Funkiness void child_handler(int sig) { int child_status; pid_t pid = wait(&child_status); printf("Received signal %d from process %d\n", sig, pid); } May lose signals no queue handler called when at least one process needs to be reaped solution?

Loop until all signals caught void child_handler(int sig) { int child_status; pid_t pid; while ((pid = wait(&child_status)) > 0) { ccount--; printf("Received signal %d from process %d\n", sig, pid); } Some interesting demos ch08/sig/alarm ch08/sig/stop

Remember the Shell? void 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); Kernel sends SIGCHLD signal to parent when child exits Install SIGCHLD handler in parent to reap process

Non-local Jumps

Try-Catch in C++ How do we transfer control from throw to catch? int divide(int num, int den ) { if (den == 0) throw logic_error(“divide by zero”); return num/den; } void process( ) { ... int q = divide(3, 0); int main( ) { try { process( ); } catch (const logic_error& e) { cerr << e.what( ) << endl; How do we transfer control from throw to catch?

setjmp/longjmp A user-level mechanism for transferring control to an arbitrary location. Way to break the procedure call/return discipline Useful for error recovery and signal handling int setjmp(jmp_buf j) Save registers, including ESP/EIP in jmp_buf Return twice. First time 0, second time returns rc from longjmp void longjmp(jmp_buf j, int rc) Restore registers from jmp_buf Set %eax (the return value) to rc Jump to the location indicated by the EIP stored in jump jmp_buf Causes original setjmp to return rc

setjmp/longjmp #include <setjmp.h> jmp_buf buf; main() { if (!setjmp(buf)) { printf(“first time through\n"); else printf(“back in main due to error\n"); p1(); // p1 calls p2, which calls p3 } ... p3() { <error checking code> if (error) longjmp(buf, 1)

sigsetjmp/siglongjmp Use the following calls for long jumps from handlers: sigsetjmp(sigjmp_buf, 1) // 1 = save signal vectors siglongjmp(buf, rc) Demo ch08/sig/restart

Limitations of Long Jumps Works within stack discipline Can only long jump to environment of function that has been called but not yet completed env jmp_buf env; P1() { if (setjmp(env)) { /* Long Jump to here */ } else { P2(); } P2() { . . . P2(); . . . P3(); } P3() longjmp(env, 1); P1 P1 P2 After longjmp P2 P2 P3 Before longjmp

Limitations of Long Jumps Works within stack discipline Can only long jump to environment of function that has been called but not yet completed env P1 P2 At setjmp jmp_buf env; P1() { P2(); P3(); } P2() if (setjmp(env)) { /* Long Jump to here */ P3() longjmp(env, 1); P1 P2 P2 returns env X P1 P3 env At longjmp X

Try-Catch in C++ Implementation? Other issues int divide(int x, int y ) { if (den == 0) throw logic_error(“divide by zero”); return x/y; } void process( ) { ... q = divide(3, 0); int main( ) { try { process( ); } catch (const logic_error& e) { cerr << e.what( ) << endl; Implementation? try: setjmp throw: longjmp Other issues stack unwinding calls destructors must match throw-catch type

Summary Signals provide process-level exception handling Some caveats Can generate from user programs Can define effect by declaring signal handler Some caveats Very high overhead >10,000 clock cycles Only use for exceptional conditions No queues Just one bit for each pending signal type Nonlocal jumps provide exceptional control flow within process Within constraints of stack discipline