Operating Systems 371-1-1631 Summer Semester 2011 Practical Session 2, Signals 1.

Slides:



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

1 CS345 Operating Systems Φροντιστήριο Άσκησης 1.
Practical Session 2, Signals and Assignment 1
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.
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
CPSC 451 Editors and Systems Calls1 Minix editors Mined - (mined) is a simple screen editor. Elle - (elle) is a clone of Emacs. Elvis - (elvis, ex, vi)
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.
UNIX IPC CSE 121 Spring 2003 Keith Marzullo. CSE 121 Spring 2003Review of Concurrency2 Creating a UNIX process A process is created by making an exact.
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.
CSc 352 Signal Handling in Unix Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
Carnegie Mellon 1 Processes, Signals, I/O, Shell Lab : Introduction to Computer Systems Recitation 9: 10/21/2013 Tommy Klein Section B.
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”
Practical Session 2, Signals and Assignment 1
Operating Systems Chapter 2
* POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm Topics.
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, 122 Practical Session 2, Signals and Assignment 1 1.
Concurrent Processes Processes can concurrently run same program. Processes can concurrently run same program. Processes can start other processes. Processes.
Operating Systems Process Creation
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 *
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.
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/
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.
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.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
Operating Systems Practical Session 3, Signals 1.
UNIX signals.
G.Jyostna.
Recitation 7 (Oct. 25) Outline Minglong Shao Office hours: Reminders
Task Control: Signals and Alarms Chapter 7 and 8
Unix Process Management
Exceptional Control Flow
Example questions… Can a shell kill itself? Can a shell within a shell kill the parent shell? What happens to background processes when you exit from.
Tarek Abdelzaher Vikram Adve Marco Caccamo
Exceptional Control Flow
Practical Session 3, Signals
Exceptional Control Flow Part II
Exceptional Control Flow
תרגול 8 – ק/פ ותקשורת תהליכים ב-Linux
CSC Advanced Unix Programming, Fall 2015
Exceptional Control Flow
Exceptional Control Flow
Exceptional Control Flow
Signals.
Exceptional Control Flow
Exceptional Control Flow
Presentation transcript:

Operating Systems Summer Semester 2011 Practical Session 2, Signals 1

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. 2

Reacting to Signals Signals are processed after a process returns from an interrupt (e.g. returning from a system call). On finishing a system call, before returning to application code, signals are dealt with (if there are any). On returning from a timer interrupt (interrupt sent by the hardware clock). 3

Signals-Asynchronous mode Programs are synchronous: executed line by line Signals can be synchronous or asynchronous – Synchronous: Dividing by zero – Asynchronous: receiving a termination signal from a different process.  It is not safe to call all functions, such as printf, from within a signal handler. A useful technique 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 4

Signals-Examples SIGSEGV - Segmentation Faults SIGFPE- Floating Point Error SIGTSTP – Causes process to suspend itself SIGCONT – Causes suspended process to resume execution. Which are synchronous? 5

Signal Table Each process has a signal table Each signal has an entry in the table Each signal has a column whether to ignore the signal or not (SIG_IGN). Each signal has a column of what to do on receiving the signal (if not ignoring it). 6 ActionSIG_IGNSig_Num 1 2

Blocking and Ignoring Blocking: The signal is received but not dealt with. It is kept in the signal table until the block is removed. Ignoring: The signal is received and discarded without any action being taken. 7

Signal Handlers Each signal has a default action – SIGTERM – Terminate process. – SIGFPE (floating point exception) –dump core and exit. The action can be changed by the process using the signal * /sigaction system call. *It is highly recommended you refrain from using the signal call in your code. Nonetheless it is important to know it since it appears in many older programs. 8

Signal Handlers Five default options: – Exit: forces the process to exit. – Core: forces the process to exit and create a core file. – Stop: stops the process. – Ignore: ignores the signal; no action taken. – Continue: Resume execution of stopped process. 9

Signal Handlers Two signals cannot be ignored or have their associated action changed: – SIGKILL – SIGSTOP (not the same as SIGTSTP used for suspension) When calling execvp() all signals are set to their default action. The bit that specifies whether to ignore the signal or not is preserved. Why? 10

Scheme of signal processing 11 User Mode Kernel Mode Normal program flow do_signal() handle_signal() setup_frame() Signal handler Return code on the stack system_call() sys_sigreturn() restore_sigcontext()

Sending Signals Signals can be sent: – From the keyboard – From the command line via the shell – Using system calls 12

Keyboard Signals Ctrl–C – Sends a SIGINT signal. By default this causes the process to terminate Ctrl-\ - Sends a SIGABRT signal. Causes the process to terminate. Ctrl-Z – Sends a SIGTSTP signal. By default this causes the process to suspend execution. 13

Command line Signals kill kill - – Sends the specified signal to the specified PID. A Negative PID specifies a whole process group. – Kill -9 is SIGKILL which kills a process. killall killall can be used to send multiple signals to processes running specific commands fg fg - Resumes the execution of a suspended process (sends a SIGCONT). 14

System call Signals Kill(pid_t pid,int sig) #include /* standard unix functions, like getpid() */ #include /* various type definitions, like pid_t */ #include /* 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); 15

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 Delivered in guaranteed order Use SIGRTMIN+n up to SIGRTMAX to refer to these signals (32 in Linux) 16

Manipulation of Signals sighandler_t signal(int signum, sighandler_t handler) Installs 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, then the signal is ignored. If the handler is set to SIG_DFL, then the default action associated with the signal occurs. 17

sigaction Manipulation of Signals sigaction int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); A more sophisticated (and safe) way of manipulating signals. Doesn’t restore signal handler to default after calling signal. signum is the number of the signal act is a pointer to a struct containing much information including the new signal handler oldact if not null will receive the old signal handler. For more details and another example see: 18 Example

Example 1 #include /* standard I/O functions */ #include /* standard unix functions, like getpid() */ #include /* various type definitions, like pid_t*/ #include /* signal name macros, and the signal() prototype */ /* first, here is the signal handler */ void catch_int(int sig_num){ /* re-set 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' */ signal(SIGINT, catch_int); /* now, lets get into an infinite loop of doing nothing. */ while (true) { pause(); } Causes the process to halt execution until it receives a signal. 19

Example 2 int cpid[5]; //holds the pids of the children int j; //pointer to cpid int sigCatcher(){ // function to activate when a signal is caught signal(SIGINT,sigCatcher); //reset the signal catcher printf("PID %d caught one\n",getpid()); if(j>-1) kill(cpid[j],SIGINT); //send signal to next child in cpid } 20

Example 2-Continued int main(){ int i; int zombie; int status; int pid; signal(SIGINT,sigCatcher); // set the signal catcher to sigCatcher 21

Example 2-Continued 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; } sleep(2); // allow children time to enter pause kill(cpid[4],SIGINT); // send signal to first child sleep(2); // wait for children to become zombies for(i=0;i<5;i++){ zombie = wait(&status); // collect zombies printf("%d is dead\n",zombie); } exit(0); } 22

Output PID ready PID ready PID ready PID ready PID ready PID caught one PID caught one PID caught one PID caught one PID caught one is dead is dead is dead is dead is dead 23

Security Issues Not all processes can send signals to all processes. Only the kernel and super user can send signals to all processes. Normal processes can only send signals to processes owned by the same user. 24

Process ID ID Each process has an ID (pid). group ID Each process has a group ID (pgid). group leader One process in the group is the group leader and all member’s group ID is equal to the leaders pid. A signal can be sent to a single process or to a process group. 25

Process Group ID process group A process group is a collection of related processes process-group identifier (pgid) All processes in a process group are assigned the same process-group identifier (pgid). The process-group identifier is the same as the PID of the process group's initial member. Used by the shell to control different tasks executed by it. 26

Process ID int getpid() – return the process’s PID. int getpgrp() – return the process’s PGID. setpgrp() – set this process’s PGID to be equal to his PID. setpgrp(int pid1, int pid2) – set process’s pid1 PGID to be equal to pid2’s PID. 27

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

Question from midterm 2004 #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); } my_prog.c 29

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

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 31

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

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

More Information _intr()&source=bl&ots=JCjEvqiVM- &sig=z8CtaNgkFpa1MPQaCWjJuU5tq4g&hl=en&ei=zf3zSZsvjJOwBs- UxYkB&sa=X&oi=book_result&ct=result&resnum=22#PPA159,M1 man signal, sigaction… man kill… Process groups: