Practical Session 3, Signals

Slides:



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

More on Processes Chapter 3. Process image _the physical representation of a process in the OS _an address space consisting of code, data and stack segments.
1 CS345 Operating Systems Φροντιστήριο Άσκησης 1.
15-213, Fall 06 Outline Shell Lab Processes Signals.
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
Page 1 Task Control: Signals and Alarms Chapter 7 and 8 B. Ramamurthy.
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.
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.
CSc 352 Signal Handling in Unix Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
UNIX Signals Bach 7.2 Operating Systems Course The Hebrew University Spring 2010.
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.
Practical Session 2, Signals and Assignment 1
Operating Systems Chapter 2
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
Operating Systems CSE 411 CPU Management Sept Lecture 9 Instructor: Bhuvan Urgaonkar.
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
Unix Process Model Simple and powerful primitives for process creation and initialization. fork syscall creates a child process as (initially) a clone.
Operating Systems Process Creation
Outline for Today Objectives –Finish discussion of Birrell –UNIX Signals –Eraser Administrative –Spider talk after class.
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 *
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.
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.
Signals & Message queue Inter process mechanism in Linux system 3/24/
Operating Systems CMPSC 473 Signals, Introduction to mutual exclusion September 28, Lecture 9 Instructor: Bhuvan Urgaonkar.
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)
System calls for Process management Process creation, termination, waiting.
Operating Systems Unit 2: – Process Context switch Interrupt Interprocess communication – Thread Thread models Operating Systems.
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.
Operating Systems Practical Session 3, Signals 1.
Operating Systems Summer Semester 2011 Practical Session 2, Signals 1.
UNIX signals.
Recitation 7 – 3/18/02 Outline fork and scheduling Signals
G.Jyostna.
Recitation 7 (Oct. 25) Outline Minglong Shao Office hours: Reminders
Signals What is a Signal?
Task Control: Signals and Alarms Chapter 7 and 8
Using Processes.
Unix Process Management
Exceptional Control Flow
Exceptional Control Flow
Exceptional Control Flow Part II
Structure of Processes
Processes in Unix, Linux, and Windows
Exceptional Control Flow
Chapter 4: Threads.
תרגול 8 – ק/פ ותקשורת תהליכים ב-Linux
CSC Advanced Unix Programming, Fall 2015
Processes in Unix, Linux, and Windows
Exceptional Control Flow
Signals Tanzir Ahmed CSCE 313 Fall 2018.
Exceptional Control Flow
Exceptional Control Flow
CSE 451: Operating Systems Autumn 2004 Module 4 Processes
Signals.
Exceptional Control Flow
Chapter 3 Process Description and Control
Exceptional Control Flow
Presentation transcript:

Practical Session 3, Signals Operating Systems Practical Session 3, Signals

Signals Signals are a way of sending simple messages to processes. Used to notify a process of important events. Signals can be sent by other processes, or by the kernel. Signals are defined in POSIX. Signals can be found in Linux but not in XV6, you can add them yourself! A mechanism for inter-process communication.

Signals-Examples SIGSEGV – Segmentation Faults SIGFPE – Floating Point Error SIGSTOP – Causes process to suspend itself SIGCONT – Causes a suspended process to resume execution A list of signals in Linux: http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/Building/files/signals.pdf SIGFPE – erroneous arithmetic operation such as division by zero http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_21.html Signals may be generated synchronously or asynchronously. A synchronous signal pertains to a specific action in the program, and is delivered (unless blocked) during that action. Errors generate signals synchronously, and so do explicit requests by a process to generate a signal for that same process. Asynchronous signals are generated by events outside the control of the process that receives them. These signals arrive at unpredictable times during execution. External events generate signals asynchronously, and so do explicit requests that apply to some other process. A given type of signal is either typically synchrous or typically asynchronous. For example, signals for errors are typically synchronous because errors generate signals synchronously. But any type of signal can be generated synchronously or asynchronously with an explicit request.

Kernel Signals Data-Structures (Linux)

Signal Table Each process has a signal table Each signal has an entry in the table Each signal has an indicator whether to ignore the signal or not (SIG_IGN) Each signal has a column of what to do upon receiving the signal (if not ignoring it) Handler FLAGS (IGN, BLK) Sig_Num 1 2

Blocking and Ignoring Blocking: The signal is not delivered to the process. It remains pending until the block is removed, Implementation: the kernel sets the blocked signal bit but does not ‘call’ the signal handler. Ignoring: The signal is discarded by the kernel without any action being taken. The execution of the process continues even if non-meaningful (i.e. ignoring SIGFPE or SIGSEGV). Implementation: the kernel does not set the ignored signal bit in the signal table. raise(int sig) is equivalent to kill(getpid(), sig) Checking the status of signals: cat /proc/<pid>/status If I want to see caught or blocked signals: cat /proc/<pid>/status | grep -E "Sig(Cgt|Blk)"

Signal Handlers Each signal has a default action. For example: SIGKILL – Terminate process. SIGFPE (floating point exception) – dump core and exit. The default action can be changed by the process using the signal*/ sigaction system call.

Signal Handlers Two signals cannot be ignored or have their associated action changed: SIGKILL SIGSTOP Fork will not change the signal handlers but clears the pending signals. When calling execvp() all signals are set to their default action. The bit that specifies whether to ignore the signal or not is preserved. The signal handlers are set to default because the whole process image is replaced. The ignore bit is preserved to allow control of the child process, i.e. nohup command which allows to continue execution of a process even if the ssh session is terminated.

Default Signal Handlers Five default actions: Ignore: ignores the signal; no action taken. Exit: forces the process to exit. Core: forces the process to exit and create a core file. Stop: stops the process. Continue: resume execution of a stopped process. Some functions are not safe to call from within a signal handler, such as printf, malloc, etc. A useful technique to overcome this is to use a signal handler to set a flag and then check that flag from the main program and print a message if required. Further reading: http://www.ibm.com/developerworks/linux/library/l-reent/index.html Non reentrant functions which manipulate static data, such as malloc, printf. For example, malloc manipulates a linked list of free blocks, and list may be in an intermediate state if interrupted.

Pending Signals Each process has a pending signals bit array Each bit represents one signal When a signal is received the kernel will set the corresponding bit After signal handled, the kernel will clear the bit … SIGINT SIGHUP 1

Signal Priority Each pending signal is marked by a bit in a 32 bit word. Therefore there can only be one signal pending of each type. A process can’t know which signal came first. The process executes the signals starting at the lowest numbered signal. POSIX 2001 also defines a set of Real-Time Signals which behave differently: Multiple instances may be queued Provide richer information (may be accompanied by an integer) Delivered in guaranteed order Use SIGRTMIN+n up to SIGRTMAX to refer to these signals (32 in Linux)

Interfacing with Signals (Linux)

Reacting to Signals Signals are processed (by the kernel) after a process finished running in kernel mode, just before returning to user mode: Upon returning from a system call. Upon returning from a interrupt (e.g., interrupt sent by the hardware clock).

Scheme of signal processing User Mode Kernel Mode Normal program flow An event which traps to kernel do_signal() handle_signal() setup_frame() Signal handler Signals are checked and processed before a process returns to user mode. This could be after a system call, after it is continued by the scheduler, or by an instruction which caused an interrupt (i.e. division by zero). Do_signal loops until there are no pending signals left. Handle_signal then calls setup_frame, which modifies the process stack in user mode in order to save the process context (sigcontext). After the context is stacked, the function stacks a system call (sigreturn) which will be executed after the signal handler in order to recover the stack data and to reinstate the saved signal mask and the original user stack, if stack changes occurs during the processing of the signal. Finally, the function modifies the instruction register in user mode so that it can execute the diversion function. system_call() sys_sigreturn() restore_sigcontext() Return code on the stack

Signals: Synchronous VS. Asynchronous Programs are synchronous: executed line by line Signals can be synchronous or asynchronous Synchronous: occur as a direct result of the executing instruction stream. Examples: dividing by zero, segmentation fault, etc. Asynchronous: external (and in some cases unrelated) to the current execution context. A mechanism for an inter-process communication. Example: receiving a termination signal from a different process.

Sending Signals Signals can be sent: Using system calls Kernel Notifications

System call Signals Kill(pid_t pid,int sig) Usage example: #include <unistd.h> /* standard unix functions, like getpid() */ #include <sys/types.h> /* various type definitions, like pid_t */ #include <signal.h> /* signal name macros, and the kill() prototype */ /* first, find my own process ID */ pid_t my_pid = getpid(); /* now that I got my PID, send myself the STOP signal. */ kill(my_pid, SIGSTOP);

Keyboard Signals (sent by shell via system call) Ctrl–C – Sends a SIGINT signal . By default this causes the process to terminate. Ctrl-\ - Sends a SIGQUIT signal. Causes the process to terminate. Ctrl-Z – Sends a SIGTSTP signal. By default this causes the process to suspend execution. Note: not all keyboard signals are supported in all shells.

Command line Signals (sent by shell via system call) kill <signal> <PID> – Sends the specified signal to the specified PID. A Negative PID specifies a whole process group. Kill -9 <PID> sends a SIGKILL which terminates the process. killall <args> <commands> – can be used to send multiple signals to all processes running specific commands. Example: killall -9 java fg – Resumes the execution of a suspended process (sends a SIGCONT).

The system call alarm unsigned alarm(unsigned seconds); Requests the system to generate a SIGALRM for the process after seconds time have elapsed. Processor scheduling delays may prevent the process from handling the signal as soon as it is generated. If seconds is 0, a pending alarm request, if any, is canceled. Alarm requests are not stacked; only one SIGALRM generation can be scheduled in this manner. If the SIGALRM signal has not yet been generated, the call shall result in rescheduling the time at which the SIGALRM signal is generated.

Kernel Notification Signals Floating point exception (SIGFPE) Division by zero Segmentation Fault (SIGSEGV)

Manipulation of Signals sighandler_t signal(int signum, sighandler_t handler) Registers a new signal handler for the signal with number signum. The signal handler is set to sighandler which may be a user specified function, or either SIG_IGN or SIG_DFL. If the corresponding handler is set to SIG_IGN or SIG_DFL, then the signal is ignored or set do default action accordingly. Return Value: previous value of the signal handler, or SIG_ERR on error. Deprecated, do not use!

Manipulation of Signals On some systems (e.g. System V Unix), if the handler is set to a function sighandler and a signal is received, then first the handler is reset to SIG_DFL, and next sighandler is called. This may result in portability issues, or unwanted signal handling. One solution to this problem is demonstrated in the “ouch” signal handler function: void ouch(int sig) { printf(“OUCH! - I got signal %d\n”, sig); signal(SIGINT, ouch); } What is the problem with this solution? Answer: if the system does not block all other signals during signal handling, a new signal may come in before we re-assign the signal handler.

Waiting for signals int pause(void); Causes the calling process (or thread) to sleep until a (any) signal is delivered that either terminates the process or causes the invocation of a signal-catching function. int sigsuspend(const sigset_t *mask); Temporarily replaces the signal mask of the process, and suspends the process until a signal not belonging to the waiting mask arrives. Allows waiting for a particular signal.

Alternative to the signal syscall A more sophisticated (and safe) way of manipulating signals is by using the sigaction (and related methods). We will not cover these on this course you can read more about them in the nearest MAN.

Examples

Example 1 #include <stdio.h> /* standard I/O functions */ #include <unistd.h> /* standard unix functions, like getpid() */ #include <sys/types.h> /* various type definitions, like pid_t*/ #include <signal.h> /* signal name macros, and the signal() prototype */ /* first, here is the signal handler */ void catch_int(int sig_num){ /* reassign the signal handler again to catch_int, for next time */ signal(SIGINT, catch_int); /* and print the message */ printf("Don't do that\n"); } int main(){ /* set the INT (Ctrl-C) signal handler to 'catch_int' */ /* now, lets get into an infinite loop of doing nothing */ while (true) { pause(); } } Causes the process to halt execution until it receives any signal.

Example 2 int main() { int i, zombie, status, pid; // sets a handler for INT signal signal(SIGINT, sigCatcher); for (i = 0; i < 5; i++) { if ((pid = fork()) == 0) { // create new child printf("PID %d ready\n", getpid()); j = i - 1; pause(); // wait for signal exit(0); // end process (become a zombie) } else // Only father updates the cpid array. cpid[i] = pid; } // allow children time to enter pause sleep(2); // send signal to first child kill(cpid[4], SIGINT); zombie = wait(&status);// collect zombies printf("%d is dead\n", zombie); exit(0); #include <stdio.h> #include <signal.h> int cpid[5];// holds the pids of the children int j;// index to cpid  // function to activate when a signal is caught int sigCatcher() { // re-assign the signal catcher signal(SIGINT, sigCatcher); printf("PID %d caught one\n", getpid()); if (j > -1) // send signal to next child in cpid kill(cpid[j], SIGINT); }

Output PID 22899 ready PID 22900 ready PID 22901 ready PID 22902 ready PID 22903 ready PID 22903 caught one PID 22902 caught one PID 22901 caught one PID 22900 caught one PID 22899 caught one 22903 is dead 22901 is dead 22902 is dead 22899 is dead 22900 is dead

Homework

Question from midterm 2004 תלמיד קיבל משימה לכתוב תכנית שמטרתה להריץ תכנית נתונה (ברשותו רק הקובץ הבינארי) prompt ע"י שימוש ב-fork ו-execvp. בנוסף נדרש התלמיד למנוע מן המשתמש "להרוג" את התכנית ע"י הקשת ctrl-c (SIGINT) (שים לב כי התכנית prompt אינה מסתיימת לעולם). מצורף פתרון שהוצע ע"י התלמיד (my_prog.c) וכן התכנית prompt. תאר במדויק את פלט התכנית כאשר הקלט הנו: Good luck in the ^c midterm exam. האם הפתרון המוצע עונה על הגדרת התרגיל? אם תשובתך ל-ב' היא לא, כיצד היית משנה את התכנית my_prog.c (ניתן להוסיף/ לשנות שורה או שתיים בקוד לכל היותר)?

Question from midterm 2004 my_prog.c #include… void cntl_c_handler(int dummy){ signal(SIGINT, cntl_c_handler); } main (int argc, char **argv){ int waited; int stat; argv[0] = “prompt”; signal (SIGINT, cntl_c_handler); if (fork() == 0) { // son execvp(“prompt”,argv[0]); else { // father waited = wait(&stat); printf(“My son (%d) has terminated \n”,waited);

Question from midterm 2004 prompt.c (זכרו כי קוד זה אינו ניתן לשינוי ע"י התלמיד) main(int argc, char** argv){ char buf[20]; while(1) { printf(“Type something: “); gets(buf); printf(“\nYou typed: %s\n”,buf); }

Sample execution of code תאר במדויק את פלט התכנית כאשר הקלט הנו: Good luck in the ^c midterm exam. Type something: Good luck You typed: Good luck Type something: in the ^c My son 139 has terminated

Code is incorrect האם הפתרון המוצע עונה על הגדרת התרגיל? Execvp doesn’t preserve signal handlers. Therefore prompt.c doesn’t ignore ^c. This means that the process can be terminated.

Code correction אם תשובתך ל-ב' היא לא, כיצד היית משנה את התכנית my_prog.c (ניתן להוסיף/ לשנות שורה או שתיים בקוד לכל היותר)? Change signal (SIGINT, cntl_c_handler); in my_prog.c With signal (SIGINT, SIG_IGN); Add if (fork()==0){ execvp(“prompt”,argv[0]);

Question from midterm 2012 נתון קטע הקוד הבא: printf(“S”); } void sigchld_handler(int s) { printf(“S”); } int main(){ signal(SIGCHLD, sigchld_handler); signal_block(SIGCHLD); if (fork() != 0) { printf(“A”); signal_unblock(SIGCHLD); printf(“B”); wait (); printf(“C”); else { printf(“D”);

Question from midterm 2012 ידוע כי הפקודות signal_block וכן signal_unblock חוסמות ומשחררות חסימה לסיגנלים. שרטטו גרף מכוון המתאר את הפלטים האפשריים לקוד זה. כל צומת בגרף תסמל הדפסה וכל קשת מכוונת תייצג יחס סדר מתחייב בין הדפסות. לדוגמא, אם עפ"י קוד מסוים ידוע כי יודפסו X, Y ו – Z וכי ההדפסה של X תופיע בהכרח לפני ההדפסה של Y (אך Z יכול להופיע לפני או אחרי כל אחת מן ההדפסות האחרות), יתקבל הגרף הבא: X Y Z

Question from midterm 2012 הגרף שיתקבל מהקוד: printf(“S”); } void sigchld_handler(int s) { printf(“S”); } int main(){ signal(SIGCHLD, sigchld_handler); signal_block(SIGCHLD); if (fork() != 0) { printf(“A”); signal_unblock(SIGCHLD); printf(“B”); wait (); printf(“C”); else { printf(“D”); A D B S C