Operating Systems Practical Session 3 Signals 1 Signals

  • Slides: 39
Download presentation
Operating Systems Practical Session 3, Signals 1

Operating Systems Practical Session 3, Signals 1

Signals • Signals are a way of sending simple messages to processes. • Used

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 processes the kernel. • Signals are defined in POSIX. • Signals can be found in Linux but not in XV 6, you can add them yourself! 2

Signals-Examples • • SIGSEGV – Segmentation Faults SIGFPE – Floating Point Error SIGSTOP –

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/unixcourses/Building/files/signals. pdf 3

Kernel Signals Data-Structures (Linux) 4

Kernel Signals Data-Structures (Linux) 4

Signal Table • Each process has a signal table • Each signal has an

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) Sig_Num 1 2 5 FLAGS (IGN, BLK) Handler

Blocking and Ignoring • Blocking: The signal is not delivered to the process. It

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

Signal Handlers • Each signal has a default action. For example: – SIGKILL –

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

Signal Handlers • Two signals cannot be ignored or have their associated action changed:

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

Default Signal Handlers • Five default actions: – Ignore: ignores the signal; no action

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/lreent/index. html 9

Pending Signals • Each process has a pending signals bit array • Each bit

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 10 SIGHUP SIGINT 0 1 …

Signal Priority • Each pending signal is marked by a bit in a 32

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: – – 11 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) 12

Interfacing with Signals (Linux) 12

Reacting to Signals • Signals are processed (by the kernel) after a process finished

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). 13

Scheme of signal processing User Mode Normal program flow Kernel Mode An event which

Scheme of signal processing User Mode Normal program flow Kernel Mode An event which traps to kernel do_signal() handle_signal() setup_frame() Signal handler Return code on the stack 14 system_call() sys_sigreturn() restore_sigcontext()

Signals: Synchronous VS. Asynchronous • Programs are synchronous: executed line by line • Signals

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 Synchronous instruction stream. Examples: dividing by zero, segmentation fault, etc. – Asynchronous: external (and in some cases unrelated) Asynchronous to the current execution context. A mechanism for an inter-process communication. Example: receiving a termination signal from a different process. 15

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

Sending Signals • Signals can be sent: – Using system calls – Kernel Notifications 16

System call Signals Kill(pid_t pid, int sig) Usage example: #include <unistd. h> /* standard

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); 17

Keyboard Signals (sent by shell via system call) • Ctrl–C – Sends a SIGINT

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

Command line Signals (sent by shell via system call) • kill <signal> <PID> –

Command line Signals (sent by shell via system call) • kill <signal> <PID> – Sends the specified signal to kill 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 – fg Resumes the execution of a suspended process (sends a SIGCONT). 19

The system call alarm unsigned alarm(unsigned seconds); Requests the system to generate a SIGALRM

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

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

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

Manipulation of Signals sighandler_t signal(int signum, sighandler_t handler) • Registers a new signal handler

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! 22

Manipulation of Signals • On some systems (e. g. System V Unix), if the

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 %dn”, sig); signal(SIGINT, ouch); } • What is the problem with this solution? 23

Waiting for signals int pause(void); Causes the calling process (or thread) to sleep until

Waiting for signals int pause(void); Causes the calling process (or thread) to sleep until a (any) signal is any 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. particular 24

Alternative to the signal syscall • A more sophisticated (and safe) way of manipulating

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

Examples 32

Examples 32

Example 1 #include <stdio. h> /* standard I/O functions */ #include <unistd. h> /*

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 thatn"); } 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 */ Causes the process to halt while (true) { execution until it receives pause(); any signal. } } 33

Example 2 int main() { int i, zombie, status, pid; // sets a handler

Example 2 int main() { int i, zombie, status, pid; // sets a handler for INT signal(SIGINT, sig. Catcher); #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 sig. Catcher() { // re-assign the signal catcher signal(SIGINT, sig. Catcher); printf("PID %d caught onen", getpid()); if (j > -1) // send signal to next child in cpid kill(cpid[j], SIGINT); } 34 for (i = 0; i < 5; i++) { if ((pid = fork()) == 0) { // create new child printf("PID %d readyn", 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); for (i = 0; i < 5; i++) { zombie = wait(&status); // collect zombies printf("%d is deadn", zombie); } exit(0); }

Output PID 22899 ready PID 22900 ready PID 22901 ready PID 22902 ready PID

Output PID 22899 ready PID 22900 ready PID 22901 ready PID 22902 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 35

HOMEWORK 36

HOMEWORK 36

Question from midterm 2004 #include… void cntl_c_handler(int dummy){ signal(SIGINT, cntl_c_handler); } main (int argc,

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); } } 38 my_prog. c

Question from midterm 2004 main(int argc, char** argv){ char buf[20]; while(1) { printf(“Type something:

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

Sample execution of code : תאר במדויק את פלט התכנית כאשר הקלט הנו -

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 40

Code is incorrect ? האם הפתרון המוצע עונה על הגדרת התרגיל • Execvp doesn’t

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

Code correction כיצד היית משנה את התכנית , ב' היא לא - אם תשובתך

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]); 42

Question from midterm 2012 : נתון קטע הקוד הבא void sigchld_handler(int s) { }

Question from midterm 2012 : נתון קטע הקוד הבא void sigchld_handler(int s) { } printf(“S”); int main(){ } 43 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 : הגרף שיתקבל מהקוד void sigchld_handler(int s) { } printf(“S”);

Question from midterm 2012 : הגרף שיתקבל מהקוד void sigchld_handler(int s) { } printf(“S”); int main(){ } 45 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