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.

Slides:



Advertisements
Similar presentations
Recitation 8: 10/28/02 Outline Processes Signals –Racing Hazard –Reaping Children Annie Luo Office Hours: Thursday 6:00.
Advertisements

Week Fourteen Agenda Announcements Final Exam True/False -100 questions (1 point per question) Multiple Choice - 40 questions (2 points per question)
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.
15-213, Fall 06 Outline Shell Lab Processes Signals.
System Programming Project 2 Due : 4/19...?. Foreground & Background Foreground job Foreground job Only one at moment Only one at moment Having user’s.
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 COS Goals of Today’s Lecture Overview of signals  Notifications sent to a process  UNIX signal names and numbers  Ways to generate.
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.
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)
Process states inWindows 2000 and Linux Module 2.1.
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”
Recitation 9: Section L (1:30pm - 2:20pm) Monday, October 22, 2012 Processes, Signals and Shell Lab Siddharth Dhulipalla.
The process concept (section 3.1, 3.3 and demos)  Process: An entity capable of requesting and using computer resources (memory, CPU cycles, files, etc).
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.
* 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.
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.
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.
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.
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/
ACCESS CONTROL. Components of a Process  Address space  Set of data structures within the kernel - process’s address space map - current status - execution.
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.
Recitation 7 (Oct. 25) Outline Minglong Shao Office hours: Reminders
Signals What is a Signal?
Precept 14 : Ish dup() & Signal Handling
Task Control: Signals and Alarms Chapter 7 and 8
Exceptional Control Flow Part II
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

2 Communicating with the OS System call (last lecture)  Request to the operating system to perform a task  … that the process does not have permission to perform Signal (this lecture)  Asynchronous notification sent to a process  … to notify the process of an event that has occurred User Process Operating System signalssystems calls

3 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

4 UNIX Process Control Non-Existing Process Running Foreground Process Stopped Background Process Running Background Process ↓ command ↑ Ctrl-c ↓ Ctrl-z ↑ fg ↓ kill -20 pid ↑ bg ↓ command & ↑ kill –2 pid ← fg

5 UNIX Process Control [Demo of UNIX process control using infloop.c]

6 Process Control Implementation Exactly what happens when you: Type Ctrl-c?  Keyboard sends hardware interrupt  Hardware interrupt is handled by OS  OS sends a 2/SIGINT signal Type Ctrl-z?  Keyboard sends hardware interrupt  Hardware interrupt is handled by OS  OS sends a 20/SIGTSTP signal Issue a “kill –sig pid” command?  OS sends a sig signal to the process whose id is pid Issue a “fg” or “bg” command?  OS sends a 18/SIGCONT signal (and does some other things too!)

7 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

8 Definition of Signal Signal: A notification of an event  Event gains attention of the OS  OS stops the application process immediately, sending it a signal  Default action for that signal executes –Can install a signal handler to change action  Application process resumes where it left off movl pushl call f addl movl. Process void handler(int iSig) { … } signal

9 Examples of Signals User types Ctrl-c  Event gains attention of OS  OS stops the application process immediately, sending it a 2/SIGINT signal  Default action for 2/SIGINT signal is “terminate” Process makes illegal memory reference  Event gains attention of OS  OS stops application process immediately, sending it a 11/SIGSEGV signal  Default action for 11/SIGSEGV signal is “terminate”

10 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

11 Sending Signals via Keystrokes Three signals can be sent from keyboard:  Ctrl-c  2/SIGINT signal –Default action is “terminate”  Ctrl-z  20/SIGTSTP signal –Default action is “stop until next 18/SIGCONT”  Ctrl-\  3/SIGQUIT signal –Default action is “terminate”

12 Sending Signals via Commands kill Command kill -signal pid –Send a signal of type signal to the process with id pid –Can specify either signal type name (-SIGINT) or number (-2)  No signal type name or number specified => sends 15/SIGTERM signal –Default action for 15/SIGTERM is “terminate”  Editorial: Better command name would be sendsig Examples kill – kill -SIGINT 1234  Same as pressing Ctrl-c if process 1234 is running in foreground

13 Sending Signals via Function Calls raise() int raise(int iSig);  Commands OS to send a signal of type iSig to current process  Returns 0 to indicate success, non-0 to indicate failure Example int ret = raise(SIGINT); /* Process commits suicide. */ assert(ret != 0); /* Shouldn't get here. */

14 Sending Signals via Function Calls kill() int kill(pid_t iPid, int iSig);  Sends a iSig signal to the process whose id is iPid  Equivalent to raise(iSig) when iPid is the id of current process  Editorial: Better function name would be sendsig() Example pid_t iPid = getpid(); /* Process gets its id.*/ kill(iPid, SIGINT); /* Process sends itself a SIGINT signal (commits suicide) */

15 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

16 Handling Signals Each signal type has a default action  For most signal types, default action is “terminate” A program can install a signal handler to change action of (almost) any signal type

17 Uncatchable Signals Special cases: A program cannot install a signal handler for signals of type:  9/SIGKILL –Default action is “terminate” –Catchable termination signal is 15/SIGTERM  19/SIGSTOP –Default action is “stop until next 18/SIGCONT” –Catchable suspension signal is 20/SIGTSTP

18 Installing a Signal Handler signal() sighandler_t signal(int iSig, sighandler_t pfHandler);  Installs function pfHandler as the handler for signals of type iSig  pfHandler is a function pointer: typedef void (*sighandler_t)(int);  Returns the old handler on success, SIG_ERR on error  After call, (*pfHandler) is invoked whenever process receives a signal of type iSig

19 Installing a Handler Example 1 Program testsignal.c: #define _GNU_SOURCE /* Use modern handling style */ #include static void myHandler(int iSig) { printf("In myHandler with argument %d\n", iSig); } …

20 Installing a Handler Example 1 (cont.) Program testsignal.c (cont.): … int main(void) { void (*pfRet)(int); pfRet = signal(SIGINT, myHandler); assert(pfRet != SIG_ERR); printf("Entering an infinite loop\n"); for (;;) ; return 0; }

21 Installing a Handler Example 1 (cont.) [Demo of testsignal.c]

22 Installing a Handler Example 2 Program testsignalall.c: #define _GNU_SOURCE #include static void myHandler(int iSig) { printf("In myHandler with argument %d\n", iSig); } …

23 Installing a Handler Example 2 (cont.) Program testsignalall.c (cont.): … int main(void) { void (*pfRet)(int); pfRet = signal(SIGHUP, myHandler); /* 1 */ pfRet = signal(SIGINT, myHandler); /* 2 */ pfRet = signal(SIGQUIT, myHandler); /* 3 */ pfRet = signal(SIGILL, myHandler); /* 4 */ pfRet = signal(SIGTRAP, myHandler); /* 5 */ pfRet = signal(SIGABRT, myHandler); /* 6 */ pfRet = signal(SIGBUS, myHandler); /* 7 */ pfRet = signal(SIGFPE, myHandler); /* 8 */ pfRet = signal(SIGKILL, myHandler); /* 9 */ …

24 Installing a Handler Example 2 (cont.) Program testsignalall.c (cont.): … /* Etc., for every signal. */ printf("Entering an infinite loop\n"); for (;;) ; return 0; }

25 Installing a Handler Example 2 (cont.) [Demo of testsignalall.c]

26 Installing a Handler Example 3 Program generates lots of temporary data  Stores the data in a temporary file  Must delete the file before exiting … int main(void) { FILE *psFile; psFile = fopen("temp.txt", "w"); … fclose(psFile); remove("temp.txt"); return 0; }

27 Example 3 Problem What if user types Ctrl-c?  OS sends a 2/SIGINT signal to the process  Default action for 2/SIGINT is “terminate” Problem: The temporary file is not deleted  Process terminates before remove("temp.txt") is executed Challenge: Ctrl-c could happen at any time  Which line of code will be interrupted??? Solution: Install a signal handler  Define a “clean up” function to delete the file  Install the function as a signal handler for 2/SIGINT

28 Example 3 Solution … static FILE *psFile; /* Must be global. */ static void cleanup(int iSig) { fclose(psFile); remove("temp.txt"); exit(0); } int main(void) { void (*pfRet)(int); psFile = fopen("temp.txt", "w"); pfRet = signal(SIGINT, cleanup); … raise(SIGINT); return 0; /* Never get here. */ }

29 SIG_IGN Predefined value: SIG_IGN Can use as argument to signal() to ignore signals Subsequently, process will ignore 2/SIGINT signals int main(void) { void (*pfRet)(int); pfRet = signal(SIGINT, SIG_IGN); … }

30 SIG_DFL Predefined value: SIG_DFL Can use as argument to signal() to restore default action Subsequently, process will handle 2/SIGINT signals using default action for 2/SIGINT signals (“terminate”) int main(void) { void (*pfRet)(int); pfRet = signal(SIGINT, somehandler); … pfRet = signal(SIGINT, SIG_DFL); … }

31 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

32 Race Conditions Race condition A flaw in a program whereby the correctness of the program is critically dependent on the sequence or timing of events beyond the program’s control Race conditions can occur in signal handlers…

33 Race Condition Example void addSalaryToSavings(int iSig) { int iTemp; iTemp = iSavingsBalance; iTemp += iMonthlySalary; iSavingsBalance = iTemp; } Handler for hypothetical “update monthly salary” signal

34 Race Condition Example (cont.) void addSalaryToSavings(int iSig) { int iTemp; iTemp = iSavingsBalance; iTemp += iMonthlySalary; iSavingsBalance = iTemp; } 2000 (1) Signal arrives; handler begins executing

35 Race Condition Example (cont.) void addSalaryToSavings(int iSig) { int iTemp; iTemp = iSavingsBalance; iTemp += iMonthlySalary; iSavingsBalance = iTemp; } void addSalaryToSavings(int iSig) { int iTemp; iTemp = iSavingsBalance; iTemp += iMonthlySalary; iSavingsBalance = iTemp; } 2000 (2) Another signal arrives; first instance of handler is interrupted; second instance of handler begins executing 2000

36 Race Condition Example (cont.) void addSalaryToSavings(int iSig) { int iTemp; iTemp = iSavingsBalance; iTemp += iMonthlySalary; iSavingsBalance = iTemp; } void addSalaryToSavings(int iSig) { int iTemp; iTemp = iSavingsBalance; iTemp += iMonthlySalary; iSavingsBalance = iTemp; } 2000 (3) Second instance executes to completion 2050

37 Race Condition Example (cont.) void addSalaryToSavings(int iSig) { int iTemp; iTemp = iSavingsBalance; iTemp += iMonthlySalary; iSavingsBalance = iTemp; } 2000 (4) Control returns to first instance, which executes to completion 2050 Lost 50 !!!

38 Race Conditions in General Race conditions can occur elsewhere too int iFlag = 0; void myHandler(int iSig) { iFlag = 1; } int main(void) { if (iFlag == 0) { /* Do something */ } Problem: myflag might become 1 just after the comparison! Must make sure that critical sections of code are not interrupted

39 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

40 Blocking Signals Blocking signals  To block a signal is to queue it for delivery at a later time  Differs from ignoring a signal 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()

41 Blocking Signals in General sigprocmask() int sigprocmask(int iHow, const sigset_t *psSet, sigset_t *psOldSet);  psSet : Pointer to a signal set  psOldSet : (Irrelevant for our purposes)  iHow : How to modify the signal mask –SIG_BLOCK: Add psSet to the current mask –SIG_UNBLOCK: Remove psSet from the current mask –SIG_SETMASK : Install psSet as the signal mask  Returns 0 iff successful Functions for constructing signal sets  sigemptyset(), sigaddset(), …

42 Blocking Signals Example 1 sigset_t sSet; int main(void) { int iRet; sigemptyset(&sSet); sigaddset(&sSet, SIGINT); iRet = sigprocmask(SIG_BLOCK, &sSet, NULL); assert(iRet == 0); if (iFlag == 0) { /* Do something */ } iRet = sigprocmask(SIG_UNBLOCK, &sSet, NULL); assert(iRet == 0); … }

43 Blocking Signals in Handlers How to block signals when handler is executing?  While executing a handler for a signal of type x, all signals of type x are blocked automatically  Previous “update monthly salary” race condition cannot happen!!!  When/if signal handler returns, block is removed Additional signal types to be blocked can be defined at time of handler installation…

44 Installing a Handler with Blocking sigaction() int sigaction(int iSig, const struct sigaction *psAction, struct sigaction *psOldAction);  iSig : The type of signal to be affected  psAction : Pointer to a structure containing instructions on how to handle signals of type iSig, including signal handler name and which signal types should be blocked  psOldAction : (Irrelevant for our purposes)  Installs an appropriate handler  Automatically blocks signals of type iSig  Returns 0 iff successful Note: More powerful than signal()

45 Blocking Signals Example 2 Program testsigaction.c: #define _GNU_SOURCE #include static void myHandler(int iSig) { printf("In myHandler with argument %d\n", iSig); } …

46 Blocking Signals Example 2 (cont.) Program testsigaction.c (cont.): … int main(void) { int iRet; struct sigaction sAction; sAction.sa_flags = 0; sAction.sa_handler = myHandler; sigemptyset(&sAction.sa_mask); iRet = sigaction(SIGINT, &sAction, NULL); assert(iRet == 0); printf("Entering an infinite loop\n"); for (;;) ; return 0; }

47 Blocking Signals Example 2 (cont.) [Demo of testsigaction.c]

48 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

49 Predefined Signals List of the predefined signals: $ kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX See Bryant & O’Hallaron book for default actions, triggering events Applications can define their own signals with unused values

50 Summary Signals  A signal is an asynchronous event  raise() or kill() sends a signal  signal() installs a signal handler –Most signals are catchable  Beware of race conditions  sigprocmask() blocks signals in any critical section of code –Signals of type x automatically are blocked while handler for type x signals is running  sigaction() installs a signal handler, and allows blocking of additional signal types during handler execution

51 Summary Q: How does the OS communicate to application programs? A: Signals For more information: Bryant & O’Hallaron, Computer Systems: A Programmer’s Perspective, Chapter 8

52 Outline 1.UNIX Process Control 2.Signals 3.Sending Signals 4.Handling Signals 5.Race Conditions 6.Blocking Signals 7.Conclusion 8.(optional) Alarms and Interval Timers

53 Alarms alarm() unsigned int alarm(unsigned int uiSec);  Sends 14/SIGALRM signal after uiSec seconds  Cancels pending alarm if uiSec is 0  Uses real time, alias wall-clock time –Time spent executing other processes counts –Time spent waiting for user input counts  Return value is meaningless Used to implement time-outs

54 Alarm Example 1 Program testalarm.c: #define _GNU_SOURCE #include static void myHandler(int iSig) { printf("In myHandler with argument %d\n", iSig); /* Set another alarm. */ alarm(2); } …

55 Alarm Example 1 (cont.) Program testalarm.c (cont.): … int main(void) { void (*pfRet)(int); sigset_t sSet; int iRet; /* Make sure that SIGALRM is not blocked. Compensates for Linux bug. */ sigemptyset(&sSet); sigaddset(&sSet, SIGALRM); iRet = sigprocmask(SIG_UNBLOCK, &sSet, NULL); assert(iRet == 0); pfRet = signal(SIGALRM, myHandler); assert(pfRet != SIG_ERR); …

56 Alarm Example 1 (cont.) Program testalarm.c (cont.): … /* Set an alarm. */ alarm(2); printf("Entering an infinite loop\n"); for (;;) ; return 0; }

57 Alarm Example 1 (cont.) [Demo of testalarm.c]

58 Alarm Example 2 Program testalarmtimeout.c: #define _GNU_SOURCE #include static void myHandler(int iSig) { printf("\nSorry. You took too long.\n"); exit(EXIT_FAILURE); }

59 Alarm Example 2 (cont.) Program testalarmtimeout.c (cont.): int main(void) { int i; void (*pfRet)(int); sigset_t sSet; int iRet; /* Make sure that SIGALRM is not blocked. */ sigemptyset(&sSet); sigaddset(&sSet, SIGALRM); iRet = sigprocmask(SIG_UNBLOCK, &sSet, NULL); assert(iRet == 0); …

60 Alarm Example 2 (cont.) Program testalarmtimeout.c (cont.): … pfRet = signal(SIGALRM, myHandler); assert(pfRet != SIG_ERR); printf("Enter a number: "); alarm(5); scanf("%d", &i); alarm(0); printf("You entered the number %d.\n", i); return 0; }

61 Alarm Example 2 (cont.) [Demo of testalarmtimeout.c]

62 Interval Timers setitimer() int setitimer(int iWhich, const struct itimerval *psValue, struct itimerval *psOldValue);  Sends 27/SIGPROF signal continually  Timing is specified by psValue  psOldValue is irrelevant for our purposes  Uses virtual time, alias CPU time –Time spent executing other processes does not count –Time spent waiting for user input does not count  Returns 0 iff successful Used by execution profilers

63 Interval Timer Example Program testitimer.c: #define _GNU_SOURCE #include static void myHandler(int iSig) { printf("In myHandler with argument %d\n", iSig); } …

64 Interval Timer Example (cont.) Program testitimer.c (cont.): … int main(void) { int iRet; void (*pfRet)(int); struct itimerval sTimer; pfRet = signal(SIGPROF, myHandler); assert(pfRet != SIG_ERR); …

65 Interval Timer Example (cont.) Program testitimer.c (cont.): … /* Send first signal in 1 second, 0 microseconds. */ sTimer.it_value.tv_sec = 1; sTimer.it_value.tv_usec = 0; /* Send subsequent signals in 1 second, 0 microseconds intervals. */ sTimer.it_interval.tv_sec = 1; sTimer.it_interval.tv_usec = 0; iRet = setitimer(ITIMER_PROF, &sTimer, NULL); assert(iRet != -1); printf("Entering an infinite loop\n"); for (;;) ; return 0; }

66 Interval Timer Example (cont.) [Demo of testitimer.c]

67 Summary Alarms  Call alarm() to deliver 14/SIGALRM signals in real/wall- clock time  Alarms can be used to implement time-outs Interval Timers  Call setitimer() to deliver 27/SIGPROF signals in virtual/CPU time  Interval timers are used by execution profilers