1 Signals COS 217. 2 Goals of Today’s Lecture Overview of signals  Notifications sent to a process  UNIX signal names and numbers  Ways to generate.

Slides:



Advertisements
Similar presentations
Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
Advertisements

2.3 InterProcess Communication (IPC) Part A. IPC methods 1. Signals 2. Mutex (MUTual EXclusion) 3. Semaphores 4. Shared memory 5. Memory mapped files.
1 Select and poll and Signals CS 241 April 6, 2012 University of Illinois.
1 Signals. 2 Communicating with the OS System call (last lecture)  Request to the operating system to perform a task  … that the process does not have.
Process Process: the UNIX abstraction of a stand-along computer that manages resources (memory, CPU, I/O resources) comprising a running program. Processes.
CS Lecture 17 Outline Named pipes Signals Lecture 17
Signals Hua LiSystems ProgrammingCS2690Signals. Topics: Sending Signals -- kill(), raise() Signal Handling -- signal() sig_talk.c -- complete example.
Operating Systems Course Hebrew University Spring 2007 Signals & User Thread.
Slide 6-1 Copyright © 2004 Pearson Education, Inc. Operating Systems: A Modern Perspective, Chapter 6 Threads and Scheduling 6.
1 Signals. 2 Context of Remaining Lectures Second half of COS 217 takes 2 tours: 1.“Language levels” tour C → assembly language → machine language Illustrated.
CS Lecture 16 Outline Inter-process Communication (IPC) – Pipes – Signals Lecture 161CS Operating Systems 1.
Signal Signal : - is a notification sent to a process to notify it of some event - interrupts whatever the process is doing and force it to handle a signal.
Section A (March 14) Outline Exceptions Process Signals Non-local jumps Reminders Lab4: Due Next Thursday TA: Kun Gao Shamelessly Modified from Minglong.
Signals, Synchronization CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han.
B. RAMAMURTHY Pag e 1 Task Control: Signals and Alarms Chapter 7 and 8 7/2/2015.
CSc 352 Signal Handling in Unix Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
COMP5102 Lecture 4 Operating Systems (OS) Inter-process Communication phones off (please)
UNIX Signals Bach 7.2 Operating Systems Course The Hebrew University Spring 2010.
Signals & Timers CS241 Discussion Section Spring 2009 Week 6.
1Reference “Introduction To Unix Signals Programming” in the reference material section Man page – sigprocmask, alarm “Understanding the Linux Kernel”
The kernel considers each program running on your system to be a process A process lives as it executes, with a lifetime that may be short or long A process.
Operating Systems CSE 411 CPU Management Sept Lecture 9 Instructor: Bhuvan Urgaonkar.
* POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm Topics.
Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
Agenda  Working with Processes: Purpose Running Programs within same process (execl, execlp, execle, execv, execvp, execve) “Spawning” other process (fork,
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R S I X Exception Handling.
Scis.regis.edu ● CS 468: Advanced UNIX Class 5 Dr. Jesús Borrego Regis University 1.
Signals (Chap 10 in the book “Advanced Programming in the UNIX Environment”) Acknowledgement : Prof. Y. Moon at Kangwon Nat’l Univ.
Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
UNIX Socket Programming CS 6378 Project Reference Book: Unix Network programming: Networking APIs: Sockets and XTI (2nd edition), Prentice Hall >> Threads.
Concurrent Processes Processes can concurrently run same program. Processes can concurrently run same program. Processes can start other processes. Processes.
Signals and Signal Processing CIS 370 Lab 7 Umass Dartmouth.
Outline for Today Objectives –Finish discussion of Birrell –UNIX Signals –Eraser Administrative –Spider talk after class.
Signals and Signal Handling. Signals A predefined message sent between two processes or from the kernel to a process, or by a user to a process A software.
Signals (Chap 10 in the book “Advanced Programming in the UNIX Environment”) Acknowledgement : Prof. Y. Moon at Kangwon Nat’l Univ.
NCHU System & Network Lab Lab #8 Signals Operating System Lab.
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 *
Interprocess Communication Mechanisms. IPC Signals Pipes System V IPC.
Operating Systems Recitation 4, April th, 2002 Signals.
Signals. Introduction r A signal is a mechanism for notifying a process that an event has occurred. m When a signal is sent to a process is normal execution.
CSC Advanced Unix Programming, Fall, 2008 Welcome back to UNIX System Programming! Monday, September 22, class 5.
1 UNIX System Programming Signals. 2 Overview 1. Definition 2. Signal Types 3. Generating a Signal 4. Responding to a Signal 5. Common Uses of Signals.
KUKUM Real Time System Module #3 POSIX programming Lecture 2.
© 숙대 창병모 1 제 10 장 신호 (Signal). © 숙대 창병모 2 Contents 1. Signal Concepts 2. signal() 3. Interrupted System Calls 4. kill() /raise() 5. alarm() pause() 6.
Today’s topic Environment variables Signal. The list of environment variables –try ‘env’ –Environment variables can be defined in shell setenv DISPLAY.
Linux/UNIX Programming APUE (Signals) [Ch. 10] 최미정 강원대학교 컴퓨터과학전공.
Today’s topics Signals and how to control the program behavior in handling signals. Terminal I/O.
Signals & Message queue Inter process mechanism in Linux system 3/24/
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 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, Abdelzaher1 Signals.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Signals.
Operating Systems Practical Session 3, Signals 1.
Operating Systems Summer Semester 2011 Practical Session 2, Signals 1.
Operating Systems Inter-Process Communication Signals Moti Geva
UNIX signals.
G.Jyostna.
Signals What is a Signal?
Task Control: Signals and Alarms Chapter 7 and 8
Exceptional Control Flow
Exceptional Control Flow
Exceptional Control Flow
CSC Advanced Unix Programming, Fall 2015
Signals.
Signals Tanzir Ahmed CSCE 313 Fall 2018.
Exceptional Control Flow
Inter-Process Communication ENCE 360
Signals Jennifer Rexford.
Signals.
Presentation transcript:

1 Signals COS 217

2 Goals of Today’s Lecture Overview of signals  Notifications sent to a process  UNIX signal names and numbers  Ways to generate signals Signal handling  Installing signal handlers  Ignoring vs. blocking signals  Avoiding race conditions Keeping track of the passage of time  Interval timers  Real time vs. CPU time

3 Signals Event notification sent to a process at any time  An event generates a signal  OS stops the process immediately  Signal handler executes and completes  The process resumes where it left off movl pushl call foo addl movl. Process handler() { … } signal

4 Examples of Signals User types control-C  Event generates the “interrupt” signal (SIGINT)  OS stops the process immediately  Default handler terminates the process Process makes illegal memory reference  Event generates “segmentation fault” signal (SIGSEGV)  OS stops the process immediately  Default handler terminates the process, and dumps core

5 Sending Signals from Keyboard Steps  Pressing keys generates interrupts to the OS  OS interprets key sequence and sends a signal OS sends a signal to the running process  Ctrl-C  INT signal –By default, process terminates immediately  Ctrl-Z  TSTP signal –By default, process suspends execution  Ctrl-\  ABRT signal –By default, process terminates immediately, and creates a core image

6 Sending Signals From The Shell kill -  Example: kill -INT 1234 –Send the INT signal to process with PID 1234 –Same as pressing Ctrl-C if process 1234 is running  If no signal name or number is specified, the default is to send an SIGTERM signal to the process, fg (foreground)  On UNIX shells, this command sends a CONT signal  Resume execution of the process (that was suspended with Ctrl-Z or a command “ bg ”)  See man pages for fg and bg

7 Sending Signals from a Program The kill command is implemented by a system call #include int kill(pid_t pid, int sig); Example: send a signal to itself if (kill(getpid(), SIGABRT)) exit(0);  The equivalent in ANSI C is: int raise(int sig); if (raise(SIGABRT) > 0) exit(1);

8 Predefined and Defined Signals Find out the predefined signals % kill –l % HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH POLL PWR SYS RTMIN RTMIN+1 RTMIN+2 RTMIN+3 RTMAX-3 RTMAX-2 RTMAX-1 RTMAX Applications can define their own signals  An application can define signals with unused values

9 Some Predefined Signals in UNIX #define SIGHUP 1 /* Hangup (POSIX). */ #define SIGINT 2 /* Interrupt (ANSI). */ #define SIGQUIT 3 /* Quit (POSIX). */ #define SIGILL 4 /* Illegal instruction (ANSI). */ #define SIGTRAP 5 /* Trace trap (POSIX). */ #define SIGABRT 6 /* Abort (ANSI). */ #define SIGFPE 8 /* Floating-point exception (ANSI). */ #define SIGKILL 9 /* Kill, unblockable (POSIX). */ #define SIGUSR1 10 /* User-defined signal 1 (POSIX). */ #define SIGSEGV 11 /* Segmentation violation (ANSI). */ #define SIGUSR2 12 /* User-defined signal 2 (POSIX). */ #define SIGPIPE 13 /* Broken pipe (POSIX). */ #define SIGALRM 14 /* Alarm clock (POSIX). */ #define SIGTERM 15 /* Termination (ANSI). */ #define SIGCHLD 17 /* Child status has changed (POSIX). */ #define SIGCONT 18 /* Continue (POSIX). */ #define SIGSTOP 19 /* Stop, unblockable (POSIX). */ #define SIGTSTP 20 /* Keyboard stop (POSIX). */ #define SIGTTIN 21 /* Background read from tty (POSIX). */ #define SIGTTOU 22 /* Background write to tty (POSIX). */ #define SIGPROF 27 /* Profiling alarm clock (4.2 BSD). */

10 Signal Handling Signals have default handlers  Usually, terminate the process and generate core image Programs can over-ride default for most signals  Define their own handlers  Ignore certain signals, or temporarily block them Two signals are not “catchable” in user programs  KILL –Terminate the process immediately –Catchable termination signal is TERM  STOP –Suspend the process immediately –Can resume the process with signal CONT –Catchable suspension signal is TSTP

11 Installing A Signal Handler Predefined signal handlers  SIG_DFL: Default handler  SIG_IGN: Ignore the signal To install a handler, use #include typedef void (*sighandler_t)(int); sighandler_t signal(int sig, sighandler_t handler);  Handler will be invoked, when signal sig occurs  Return the old handler on success; SIG_ERR on error  On most UNIX systems, after the handler executes, the OS resets the handler to SIG_DFL

12 Example: Clean Up Temporary File Program generates a lot of intermediate results  Store the data in a temporary file (e.g., “temp.xxx”)  Remove the file when the program ends (i.e., unlink) #include char *tmpfile = “temp.xxx”; int main() { FILE *fp; fp = fopen(tmpfile, “rw”); … fclose(fp); unlink(tmpfile); return(0); }

13 Problem: What about Control-C? What if user hits control-C to interrupt the process?  Generates a SIGINT signal to the process  Default handling of SIGINT is to terminate the process Problem: the temporary file is not removed  Process dies before unlink(tmpfile) is performed  Can lead to lots of temporary files lying around Challenge in solving the problem  Control-C could happen at any time  Which line of code will be interrupted??? Solution: signal handler  Define a “clean-up” function to remove the file  Install the function as a signal handler

14 Solution: Clean-Up Signal Handler #include char *tmpfile = “temp.xxx”; void cleanup() { unlink(tmpfile); exit(1); } int main() { if (signal(SIGINT, cleanup) == SIG_ERR) fprintf(stderr, “Cannot set up signal\n”); … return(0); }

15 Ignoring a Signal Completely disregards the signal  Signal is delivered and “ignore” handler takes no action  E.g., signal(SIGINT, SIG_IGN) to ignore the ctrl-C Example: background processes (e.g., “a.out &”)  Many processes are invoked from the same terminal –And, just one is receiving input from the keyboard  Yet, a signal is sent to all of these processes –Causes all processes to receive the control-C  Solution: shell arranges to ignore interrupts –All background processes use the SIG_IGN handler

16 Example: Clean-Up Signal Handler #include char *tmpfile = “temp.xxx”; void cleanup() { unlink(tmpfile); exit(1); } int main() { if (signal(SIGINT, cleanup) == SIG_ERR) fprintf(stderr, “Cannot set up signal\n”); … return(0); } Problem: What if this is a background process that was ignoring SIGINT???

17 Solution: Check for Ignore Handler signal() system call returns previous handler  E.g., signal(SIGINT, SIG_IGN) –Returns SIG_IGN if signal was being ignored –Sets the handler (back) to SIG_IGN Solution: check the value of previous handler  If previous handler was “ignore” –Continue to ignore the interrupt signal  Else –Change the handler to “cleanup”

18 Solution: Modified Signal Call #include char *tmpfile = “temp.xxx”; void cleanup() { unlink(tmpfile); exit(1); } int main() { if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, cleanup); … return(0); } Solution: If SIGINT was ignored, simply keep on ignoring it!

19 Blocking or Holding a Signal Temporarily defers handling the signal  Process can prevent selected signals from occurring  … while ensuring the signal is not forgotten  … so the process can handle the signal later Example: testing a global variable set by a handler int myflag = 0; void myhandler() { myflag = 1; } int main() { if (myflag == 0) /* do something */ } Problem: myflag might become 1 just after the comparison!

20 Race Condition: Salary Example void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } Handler for “Monthly salary signal”

21 Race Condition: Handler Starts void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } 2000

22 Race Condition: Signal Again void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } 2000

23 Race Condition: 2 nd Handler Call void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } 2000

24 Race Condition: Back to 1 st Handler void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; }

25 Race Condition: Lost Money! You just lost a month’s worth of salary! void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; } void add_salary_to_savings() { int tmp; tmp = savingsBalance; tmp += monthlySalary; savingsBalance = tmp; }

26 Blocking Signals Why block signals?  An application wants to ignore certain signals  Avoid race conditions when another signal happens in the middle of the signal handler’s execution Two ways to block signals  Affect all signal handlers sigprocmask()  Affect a specific handler sigaction()

27 Block Signals Each process has a signal mask in the kernel  OS uses the mask to decide which signals to deliver  User program can modify mask with sigprocmask() int sigprocmask() with three parameters  How to modify the signal mask (int how) –SIG_BLOCK: Add set to the current mask –SIG_UNBLOCK: Remove set from the current mask –SIG_SETMASK : Install set as the signal mask  Set of signals to modify (const sigset_t *set)  Old signals that were blocked (sigset_t *oset) Functions for constructing sets  sigemptyset(), sigaddset(), …

28 Example: Block Interrupt Signal #include sigset_t newsigset; int main() { sigemptyset(&newsigset); sigaddset(&newsigset, SIGINT); if (sigprocmask(SIG_BLOCK, &newsigset, NULL) < 0) fprintf(stderr, “Could not block signal\n”); … }

29 Problem: Blocking Signals in Handler Goal: block certain signals within a handler  Another signal might arrive at the start of the handler  … before calling the system call to block signals Solution: install handler and the mask together  Sigaction() system call, with three parameters –Signal number (int signum) –Set new signal action (const struct sigaction *) –Examine old signal action (struct sigaction *)  Sigaction data structure –Handler for the signal –Mask of additional signals to block during the handler –Flags controlling delivery of the signal

30 Sigaction() vs. Signal() Benefits of sigaction() over signal()  Set the mask and handler together  Examine the existing handler without reassigning it  Provide handler with information about process state You should not mix the two system calls  They interact in strange ways  In Assignment #7, we recommend using sigaction()

31 Keeping Track of Passage of Time Interval timers  Generate a signal after a specific time interval Real time (or wall-clock time)  Elapsed time, independent of activity  Not an accurate measure of execution time  Timer generates a SIGALRM signal Virtual time (or CPU time)  Time the process spends running  Doesn’t include spent by other processes  Timer generates a SIGPROF signal

32 Interval Timer in Real Time Sends an SIGALRM signal after n seconds unsigned int alarm(unsigned seconds); Example #include /* signal names and API */ void catch_alarm(int sig) { if (signal(SIGALRM, catch_alarm) == SIG_ERR)...;... } main(void) { if (signal(SIGALRM, catch_alarm) == SIG_ERR)...; alarm(10);...; }

33 Interval Timer in CPU Time Send an signal after an interval timer expires #include int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue); Example: SIGPROF signal every 10 milliseconds struct itimerval timer; timer.it_value.tv_sec = 0; timer.it_value.tv_usec = 10000; /* 10ms */ timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 10000; /* reload 10ms */ if (setitimer(ITIMER_PROF, &timer, NULL) ==...)...; On Linux, the minimal effective granularity is 10ms.

34 Conclusions Signals  An asynchronous event mechanism  Use sigaction() and blocking to avoid race conditions  Signal handlers should be simple and short  Most predefined signals are “catchable” Interval timers  Real time (SIGALRM) or CPU time (SIGPROF)  Linux imposes 10ms as the minimal granularity