Shell and Signals. Computer Organization 3/17/2015. CSC252 - Spring The World of Multiprogramming or Multitasking. Unix Process Hierarchy

Similar documents
Processes & Signals. System Runs Many Processes Concurrently. State consists of memory image + register values + program counter

Lecture 24: Multitasking and Signals

Signals. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Multitasking. Programmer s model of multitasking. fork() spawns new process. exit() terminates own process

Programming Assignments will be.. All the PAs are continuous 3 major factors that you should consider

Exceptional Control Flow Exists at All Levels of a System. Systemprogrammering 2007 Föreläsning 3 Exceptional Control Flow Part II

ECF Exists at All Levels of a System Exceptional Control Flow Part II Oct. 22, 2002 Topics! Process Hierarchy! Shells! Signals!

Exceptions, Processes and Signals

Exceptional Control Flow: Signals and Nonlocal Jumps

Exceptional Control Flow Part II

Giving credit where credit is due

CS213. Exceptional Control Flow Part II. Topics Process Hierarchy Signals

Exceptional Control Flow Part II Nov. 2, 2009"

What is an Operating System? Signals, Processes, & Threads. Resource Sharing. Resource Abstraction ... Operating Systems 10/20/2010

Excep&onal Control Flow: Signals and Nonlocal Jumps

ECF Exists at All Levels of a System

Mul$tasking and Shells

Program and OS Intera/on: Mul/tasking and Signals

Operating Systems Components. What is an Operating System? Process Management. Memory Management. Operating Systems 9/7/2018 CSC 256/456 1

Last Class. System Calls, Kernel Mode, and Process Implementation. Processes. Today. Operating Systems 9/11/2018 CSC 256/456 1

Processes & Threads. (Chapter 3) CS 4410 Operating Systems. [R. Agarwal, L. Alvisi, A. Bracy, M. George, E. Sirer, R. Van Renesse]

CS 201. Processes. Gerson Robboy Portland State University

Introduction to Computer Systems , fall th Lecture, Oct. 14 th

Exceptional Control Flow Part II October 24, 2007

Operating Systems 9/6/ SIGINT Terminate Interrupt from keyboard (ctl-c) 9 SIGKILL Terminate Kill program (cannot override or ignore)

Exceptional Control Flow: Signals and Nonlocal Jumps

Foundations of Computer Systems

Processes: Introduction. CS 241 February 13, 2012

!"#$%&'()*+,'(-.'*+/*' ()*5+)(6+7'(*'#)*+89:%5 !,/+!"35-5+)-+;**+<$=$*5+'>+)+2?5-$:

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 20

Exceptional Control Flow: Signals

Exceptional Control Flow Part I

Exceptional Control Flow: Exceptions and Processes

Giving credit where credit is due

Signals, Synchronization. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han

Today. Exceptional Control Flow Processes. Exceptions and Processes. Control Flow. Altering the Control Flow

Exceptional Control Flow Part I Oct. 17, 2002

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 18

Are branches/calls the only way we can get the processor to go somewhere in a program? What is a program? A processor? A process?

Exceptional Control Flow Part I Oct. 28, 2009"

Control Flow. Systemprogrammering 2007 Föreläsning 2 Exceptional Control Flow Part I. Exceptional Control Flow. Altering the Control Flow

Exceptional Control Flow Part I September 22, 2008

Concurrent Processes. CS 475, Spring 2018 Concurrent & Distributed Systems

OS Interaction and Processes

Excep&onal Control Flow

CSC 252: Computer Organization Spring 2018: Lecture 19

Processes. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Today. Introduction to Computer Systems /18 243, Fall th Lecture. Control Flow. Altering the Control Flow.

Excep&onal Control Flow

Exceptional Control Flow Part I

Q & A (1) Where were string literals stored? Virtual Address. SSE2033: System Software Experiment 2 Spring 2016 Jin-Soo Kim

Announcement (1) sys.skku.edu is now available

Processes, Exceptional

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 19

Computer Science & Engineering Department I. I. T. Kharagpur. Operating System: CS rd Year CSE: 5th Semester (Autumn ) Lecture VII

Process Control. Philipp Koehn. 23 April 2018

University of Washington What is a process?

Exceptions, Processes and Signals

Program and OS interac0ons: Excep0ons and Processes

Excep&onal Control Flow: Excep&ons and Processes

Process Management forks, bombs, zombies, and daemons! Lecture 5, Hands-On Unix System Administration DeCal

Processes. CSE 351 Autumn Instructor: Justin Hsia

Signals. Goals of this Lecture. Help you learn about: Sending signals Handling signals

Excep onal Control Flow: Excep ons and Processes

Processes. CSE 351 Autumn Instructor: Justin Hsia

Operating System Structure

Carnegie Mellon. Processes. Lecture 12, May 19 th Alexandre David. Credits to Randy Bryant & Dave O Hallaron from Carnegie Mellon

Signals: Management and Implementation. Sanjiv K. Bhatia Univ. of Missouri St. Louis

System Calls and Signals: Communication with the OS. System Call. strace./hello. Kernel. Context Switch

Approaches to Concurrency

Exceptional Control Flow: Exceptions and Processes

CSE351 Inaugural Edi7on Spring

CSCI2467: Systems Programming Concepts

CS3733: Operating Systems

Most of the work is done in the context of the process rather than handled separately by the kernel

CSci 4061 Introduction to Operating Systems. (Advanced Control Signals)

Introduction to Computer Systems , fall th Lecture, Oct. 7 th

Excep&onal Control Flow: Signals and Nonlocal Jumps

System Programming. Signals I

Overview. Administrative. * HW 1 grades. * HW 2 Due. Topics. * 5.1 What is a Signal? * Dealing with Signals - masks, handlers

Are branches/calls the only way we can get the processor to go somewhere in a program? What is a program? A processor? A process?

KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 6

CSCI0330 Intro Computer Systems Doeppner. Project Shell 2. Due: November 8, 2017 at 11:59pm. 1 Introduction 2

CSC374, Spring 2010 Lab Assignment 1: Writing Your Own Unix Shell

System Calls & Signals. CS449 Spring 2016

Process. Signal #8. Signals are software interrupts from unexpected events. a power failure. an alarm clock. the death of a child process

Lesson 3. The func procedure allows a user to choose the action upon receipt of a signal.

Each terminal window has a process group associated with it this defines the current foreground process group. Keyboard-generated signals are sent to

Signals. Joseph Cordina

Preview. Process Termination. wait and waitpid() System Call. wait and waitpid() System Call. waitpid() System Call 10/23/2018

Processes. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

PROCESS CONTROL BLOCK TWO-STATE MODEL (CONT D)

The Kernel. wants to be your friend

CS 4410, Fall 2017 Project 1: My First Shell Assigned: August 27, 2017 Due: Monday, September 11:59PM

So far, we know how to create processes. How do we communicate with them? Primary mechanism: signals

Operating Systems 2010/2011

Operating Systems. Threads and Signals. Amir Ghavam Winter Winter Amir Ghavam

Princeton University. Computer Science 217: Introduction to Programming Systems. Signals

Advanced Unix/Linux System Program. Instructor: William W.Y. Hsu

IMPLEMENTATION OF SIGNAL HANDLING. CS124 Operating Systems Fall , Lecture 15

Transcription:

Shell and Signals Kai Shen The World of Multiprogramming or Multitasking System runs many processes concurrently Process: executing program State includes memory image + register values + program counter Regularly 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 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 1 2 Management of Concurrent Processes Unix Process Hierarchy Basic functions fork spawns new process Called once, returns twice execve runs new program in existing process Called once, (normally) never returns exit terminates own process Called once, never returns Puts it into zombie status wait and waitpid wait for and reap terminated children Daemon e.g. httpd init [1] Login shell Programming challenge Avoiding improper use of system resources (e.g. Fork bombs can disable a system) Grandchild Grandchild 3 4 CSC252 - Spring 2015 1

Shell Programs Simple Shell eval Function A shell is a program that allows users run/control programs. sh Original Unix shell (Stephen Bourne, AT&T Bell Labs, 1977) csh BSD Unix C shell (tcsh: enhanced csh at CMU and elsewhere) 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 */ bash Bourne Again Shell int main() { char cmdline[maxline]; while (1) { /* read */ printf("> "); fgets(cmdline, MAXLINE, stdin); if (feof(stdin)) /* evaluate */ eval(cmdline); Execution is a sequence of read/evaluate steps 5 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]); 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); 6 What Is a Job? Problem with Simple Shell Example Users generally run one command at a time Type command, read output, type another command Some programs run for a long time Example: delete this file in two hours 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); unix> sleep 7200; rm /tmp/junk # shell stuck for 2 hours Our example shell correctly waits for and reaps foreground jobs But what about background jobs? A background job is a process we don't want to wait for Will become zombies when they terminate unix> (sleep 7200 ; rm /tmp/junk) & [1] 907 unix> # ready for next command Will never be reaped because shell (typically) will not terminate Will create a memory leak that could run the kernel out of memory Once you exceed your process quota, your shell can't run any new commands for you: fork() returns 1 7 8 CSC252 - Spring 2015 2

Exceptional Control Flow Signals Problem The shell doesn't know when a background job will finish By nature, it could happen at any time The shell's regular control flow can't reap exited background processes in a timely fashion Regular control flow is wait until running job completes, then reap it Solution: Exceptional control flow The kernel will interrupt regular processing to alert us when a background process completes In Unix, the alert mechanism is called a signal A signal is a small message that notifies a process that an event of some type has occurred in the system akin to interrupts sent from the kernel (sometimes at the request of another process) to a process signal type is identified by small integer ID s (1 30) ID Name Default Action Corresponding Event 2 SIGINT Terminate Interrupt (e.g., ctl c from keyboard) 9 SIGKILL Terminate Kill program (cannot override or ignore) 11 SIGSEGV Terminate & Dump Segmentation violation 14 SIGALRM Terminate Timer signal 17 SIGCHLD Ignore stopped or terminated 9 10 Sending a Signal Receiving a Signal When is a signal sent? A system event such as divide by zero (SIGFPE), segmentation violation (SIGSEGV), 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 The operating system sends/delivers 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 signal handler Akin to a hardware exception handler being called in response to an asynchronous interrupt 11 12 CSC252 - Spring 2015 3

Pending and Blocked Signals A signal is pending if sent but not yet received Process Groups Every process belongs to exactly one process group A process can block the receipt of certain signals Blocked signals can be delivered, but will not be received until the signal is unblocked pid=10 pgid=10 Shell pid=20 job job #1 pid=32 pgid=32 job #2 pid=40 pgid=40 process group 32 process group 40 pid=21 process group 20 pid=22 13 14 Sending Signals with kill Sending Signals from the Keyboard kill program sends arbitrary signal to a process or process group linux>./forks 1: pid=24818 pgrp=24817 2: pid=24819 pgrp=24817 Typing ctrl c (ctrl z) sends a SIGINT (SIGTSTP) to every job in the foreground process group. SIGINT default action is to terminate each process SIGTSTP default action is to stop (suspend) each process Examples /bin/kill 9 24818 Send SIGKILL to process 24818 /bin/kill 9 24817 Send SIGKILL to every process in process group 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> /bin/kill -9-24817 linux> ps PID TTY TIME CMD 24788 pts/2 00:00:00 tcsh 24823 pts/2 00:00:00 ps linux> pid=20 job pid=10 pgid=10 Shell job #1 process group 32 pid=32 pgid=32 job #2 pid=40 pgid=40 process group 40 pid=21 pid=22 15 process group 20 16 CSC252 - Spring 2015 4

Sending Signals with kill Function Default Actions void fork_example() { pid_t pid[n]; int i, child_status; for (i = 0; i < N; i++) if ((pid[i] = fork()) == 0) while(1); /* infinite loop */ /* Parent terminates the child processes */ printf("killing process %d\n", pid[i]); kill(pid[i], SIGINT); Each signal type has a predefined default action, which 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 /* Parent reaps terminated children */ pid_t wpid = wait(&child_status); if (WIFEXITED(child_status)) printf(" %d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status)); else printf(" %d terminated abnormally\n", wpid); 17 18 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 returns, control passes back to instruction in the control flow of the process that was interrupted by receipt of the signal 19 Signal Handling Example void int_handler(int sig) { safe_printf("process %d received signal %d\n", getpid(), sig); void fork_example() { pid_t pid[n]; int i, child_status; signal(sigint, int_handler); for (i = 0; i < N; i++) linux>./forks if ((pid[i] = fork()) == 0) Killing { process 25417 while(1); /* child infinite Killing loop process 25418 Killing process 25419 Killing process 25420 printf("killing process %d\n", Killing pid[i]); process 25421 kill(pid[i], SIGINT); Process 25417 received signal 2 Process 25418 received signal 2 Process 25420 received signal 2 pid_t wpid = wait(&child_status); Process 25421 received signal 2 if (WIFEXITED(child_status)) Process 25419 received signal 2 printf(" %d terminated with 25417 exit terminated status %d\n", with exit status 0 wpid, WEXITSTATUS(child_status)); 25418 terminated with exit status 0 else 25420 terminated with exit status 0 printf(" %d terminated abnormally\n", 25419 terminated wpid); with exit status 0 25421 terminated with exit status 0 linux> 20 CSC252 - Spring 2015 5

Signals Handlers as Concurrent Flows Nonquequing Signals A signal handler is a separate logical flow (not process) that runs concurrently with the main program Time Process A while (1) ; Process A handler(){ Process B Pending signals are not queued For each signal type, just have single bit indicating whether or not signal is pending There can be at most one pending signal of any particular type, even if multiple processes have sent this signal If two signals of the same type arrive at the process before either is handled, the signal handler will only run once Are they really concurrent? Or asynchronous? Where is the stack for signal handler? You can have a dedicated signal handling stack. 21 22 A Program That Reacts to Internally Generated Events Re entrant Function #include <stdio.h> #include <signal.h> int beeps = 0; /* SIGALRM handler */ void handler(int sig) { printf("\n"); if (++beeps < 5) alarm(1); else { printf("boom!\n"); main() { signal(sigalrm, handler); alarm(1); /* send SIGALRM in 1 second */ while (1) { /* handler returns here */ linux>./internal BOOM! linux> Function is re entrant if it can be interrupted in the middle of one invocation and safely start another invocation of the same function before the previous invocation completes What kinds of functions may not be re entrant? using global, static, or even thread local temporary variables using locks may lead to deadlocks, e.g., malloc() Not the same as thread safe functions http://en.wikipedia.org/wiki/reentrancy_%28computing%29 23 24 CSC252 - Spring 2015 6

Asynchronous Signal Safety Disclaimer Function is async signal safe if either reentrant (all variables stored on stack frame) or non interruptible by signals. Posix guarantees a list of functions to be async signal safe Write() is on the list, printf() is not One solution: async signal safe wrapper for printf: These slides were adapted from the CMU course slides provided along with the textbook of Computer Systems: A programmer s Perspective by Bryant and O Hallaron. The slides are intended for the sole purpose of teaching the computer organization course at the University of Rochester. void safe_printf(const char *format,...) { char buf[maxs]; va_list args; va_start(args, format); /* reentrant */ vsnprintf(buf, sizeof(buf), format, args); /* reentrant */ va_end(args); /* reentrant */ write(1, buf, strlen(buf)); /* async-signal-safe */ 25 26 CSC252 - Spring 2015 7