號誌 (Signals). What is “signal” 2 user land kernel land system call signal (up call) hardware/software events kernel service.

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

15-213, Fall 06 Outline Shell Lab Processes Signals.
23-May-15Advanced Programming Spring 2002 Programming approaches Henning Schulzrinne Dept. of Computer Science Columbia University.
CS591 (Spring 2001) The Linux Kernel: Signals & Interrupts.
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)
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.
Advanced OS Chapter 3p2 Sections 3.4 / 3.5. Interrupts These enable software to respond to signals from hardware. The set of instructions to be executed.
1 Signals COS Goals of Today’s Lecture Overview of signals  Notifications sent to a process  UNIX signal names and numbers  Ways to generate.
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.
B. RAMAMURTHY Pag e 1 Task Control: Signals and Alarms Chapter 7 and 8 7/2/2015.
1 Process Description and Control Chapter 3 = Why process? = What is a process? = How to represent processes? = How to control processes?
CSc 352 Signal Handling in Unix Saumya Debray Dept. of Computer Science The University of Arizona, Tucson
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.
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”
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,
4061 Session 15 (3/6). Today More about signals A (relevant) aside Quiz review.
* 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.
IPC Programming. Process Model Processes can be organized into a parent-child hierarchy. Consider the following example code: /* */
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 *
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.
© 숙대 창병모 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.
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)
Signals and daemon processes Prepared by : Department of CSE Engineered for Tomorrow Course code: 10CS62.
Unix System Programming
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Signals.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Signals.
Operating Systems Practical Session 3, Signals 1.
CHAPTER 10. SIGNALS System Programming 本份投影片大量參考熊博安教授的系統程式投影片 羅習五 國立中正大學資訊工程學系 EA-001 (05) ext.
Operating Systems Summer Semester 2011 Practical Session 2, Signals 1.
Operating Systems Inter-Process Communication Signals Moti Geva
UNIX signals.
Recitation 7 – 3/18/02 Outline fork and scheduling Signals
Recitation 7 (Oct. 25) Outline Minglong Shao Office hours: Reminders
Task Control: Signals and Alarms Chapter 7 and 8
Unix Process Management
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
UNIT-IV Process and Signals
Chapter 5 (part 1) TCP Client /Server Example By: Lim Meng Hui.
Chapter 4: Threads.
CSC Advanced Unix Programming, Fall 2015
Signals.
Presentation transcript:

號誌 (Signals)

What is “signal” 2 user land kernel land system call signal (up call) hardware/software events kernel service

What is “signal” 3 time register a call back function my_sig_handler eventfunc div by 0default seg. faultdefault alarmmy_sig_handler ctr+cterminate ctr+/terminate

What is “signal” 4 time register a call back function my_sig_handler eventfunc div by 0default seg. faultdefault alarmmy_sig_handler ctr+cterminate ctr+/terminate

What is “signal” 5

UNIX Signals (BSD) 6

signal and process management 7

Lab 1 列印所有可註冊的 signal 8 1.#include 2.#include 3.#include 4.void sighandler(int signumber) { 5. printf("get a signal named '%d', '%s'\n", signumber, 6. sys_siglist[signumber]); 7.} 8.int main(int argc, char **argv) { 9. int sig_exist[100]; 10. int idx = 0; 11. for (idx = 0; idx < 100; idx++) { 12. if (signal(idx, sighandler) == SIG_ERR) {

Lab 1 列印所有可註冊的 signal 9 1. sig_exist[idx] = 0; 2. } else { 3. sig_exist[idx] = 1; 4. } 5. } 6. for (idx = 0; idx < 100; idx++) { 7. if (sig_exist[idx] == 1) 8. printf("%2d %s\n", idx, sys_siglist[idx]); 9. } 10. printf("my pid is %d\n", getpid()); 11. printf("press any key to resume\n"); 12. getchar(); 13.}

Lab 1: results (MAC OS X) 1 Hangup 2 Interrupt 3 Quit 4 Illegal instruction 5 Trace/BPT trap 6 Abort trap 7 EMT trap 8 Floating point exception 10 Bus error 11 Segmentation fault 12 Bad system call 13 Broken pipe 14 Alarm clock 15 Terminated 16 Urgent I/O condition 18 Suspended 19 Continued 20 Child exited 21 Stopped (tty input) 22 Stopped (tty output) 23 I/O possible 24 Cputime limit exceeded 25 Filesize limit exceeded 26 Virtual timer expired 27 Profiling timer expired 28 Window size changes 29 Information request 30 User defined signal 1 31 User defined signal 2 10

Lab 1: results (Linux) 1 Hangup 2 Interrupt 3 Quit 4 Illegal instruction 5 Trace/breakpoint trap 6 Aborted 7 Bus error 8 Floating point exception 10 User defined signal 1 11 Segmentation fault 12 User defined signal 2 13 Broken pipe 14 Alarm clock 15 Terminated 16 Stack fault 17 Child exited 18 Continued 20 Stopped 21 Stopped (tty input) 22 Stopped (tty output) 23 Urgent I/O condition 24 CPU time limit exceeded 25 File size limit exceeded 26 Virtual timer expired 27 Profiling timer expired 28 Window changed 29 I/O possible 30 Power failure 31 Bad system call 11

Lab 1: results (Linux) 試試看 1.kill -4 pid 2.resize your terminal window 12

Lab2: segmentation fault 試試看 ” 故意存取錯誤的記 憶體 ” 13

14 Interrupted System Calls A process is blocked in a “ slow ” device (a system call) The process receives a signal The system call is interrupted and returns an error ( errno = EINTR ) May be something happened that should wake up the blocked system call

Interrupted System Calls System calls divided into 2 categories: slow: reads from or writes to files that can block caller forever (pipes, terminals, network devs) opens of files that block until some condition occurs (terminal waiting on modem answer) pause, wait some ioctl operations interprocessor communication all others: disk I/O, etc. 15

Why? 16 rdyQ running interruptible uninterruptible fork()_exit()

Lab1: strace a.out rt_sigaction(SIGHUP, {0x4006ec, [HUP], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGINT, {0x4006ec, [INT], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGQUIT, {0x4006ec, [QUIT], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGILL, {0x4006ec, [ILL], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGTRAP, {0x4006ec, [TRAP], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGABRT, {0x4006ec, [ABRT], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGBUS, {0x4006ec, [BUS], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGFPE, {0x4006ec, [FPE], SA_RESTORER|SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = 0 rt_sigaction(SIGKILL, {0x4006ec, [KILL], SA_RESTORER| SA_RESTART, 0x7fa1045af4a0}, {SIG_DFL, [], 0}, 8) = -1 EINVAL (Invalid argument) 17

18 Reentrant Functions 1.Process is executing 2.Signal arrives and is caught 3.Signal handler starts executing 4.Signal handler returns 5.Process resumes execution summary: signal is an asynchronous event. so... Any problems?

19 time register a call back function my_sig_handler eventfunc div by 0default seg. faultdefault alarmmy_sig_handler ctr+cterminate ctr+/terminate

20 Reentrant Functions What if process was in the middle of malloc(), signal handler starts executing and also calls malloc()? malloc() maintains a linked list of all allocated areas process may have been in the middle of updating the linked list!

21 Reentrant Functions Signal handlers should only call reentrant functions! “ errno variable” updated by reentrant functions such as read(), wait(), etc. signal handler should save errno, and restore it on exit

SIGCLD Semantics signal(SIGCLD, SIG_IGN) no zombie processes for children subsequent wait() will block until all children terminated and returns -1 with errno = ECHILD different from SIG_DFL (also ignore, but without the above semantics) signal(SIGCLD, handler) kernel checks for child to be waited for if there is, kernel calls SIGCLD handler 22

SIGCHLD Semantics POSIX.1 Does not specify what happens when SIGCHLD is ignored Single UNIX Specification (XSI extension) Same as for SIGCLD 4.4BSD and FreeBSD Always generates zombies if SIGCHLD ignored SVR4, Solaris 9, Linux, Mac OS X 10.3 signal(SIGCHLD, SIG_IGN)  zombies never generated 23

Lab5 #include void sighandler(int signumber) { printf("get a signal named '%d', '%s'\n", signumber, sys_siglist[signumber]); if (signumber == SIGINT) exit(0); } int main(int argc, char **argv) { int sig_exist[100]; sigset_t sigset; int idx = 0; for (idx = 0; idx < 100; idx++) { if (signal(idx, sighandler) == SIG_ERR) { sig_exist[idx] = 0; } else { sig_exist[idx] = 1; } for (idx = 0; idx < 100; idx++) { if (sig_exist[idx] == 1) printf("%2d %s\n", idx, sys_siglist[idx]); } printf("my pid is %d\n", getpid()); sigfillset(&sigset); sigprocmask(SIG_SETMASK, &sigset, NULL); printf("sleep 10sec\n"); for(idx=0; idx<10; idx++) { sleep(1); write(1, "*", 1); } printf("\n"); sigemptyset(&sigset); sigprocmask(SIG_SETMASK, &sigset, NULL); while (1) { pause(); } 24

Lab5: results (null) 64 (null) my pid is 7276 sleep 10sec *^\^\^\^\*^\^\^\^\**^\*^\***** get a signal named '3', 'Quit' ^Cget a signal named '2', 'Interrupt' 25

kill and raise functions kill: To send a signal to a process or a process group #include int kill(pid_t pid, int signo); Both return: 0 if OK, -1 on error 26

kill(pid_t pid, int signo) pid > 0: sent to PID==pid pid < 0: sent to PGID==|pid| pid == 0: sent to all processes with PGID == PGID of sender (with perm) pid == -1: all processes on the system for which the sender has permission to send signal (excluding system processes) 27

kill function Permission to send signals: Superuser: to any process Others: real/effective ID of sender must be equal to real/effective ID of receiver 28

Figure 10.10: read with timeout 1.#include “apue.h" 2. 3.static void sig_alrm(int); 4. 5.int main(void) 6.{ 7. int n; 8. char line[MAXLINE]; if (signal(SIGALRM, sig_alrm) == SIG_ERR) 11. err_sys("signal(SIGALRM) error"); 12. alarm(10); 13. if ( (n = read(STDIN_FILENO, line, MAXLINE)) < 0) 14. err_sys("read error"); 15. alarm(0); write(STDOUT_FILENO, line, n); exit(0); 20.} 29 race condition between alarm and read, set minute- long time delay to circumvent race read not interrupted if interrupted system calls are automatically restarted 比較好的寫法應該 是用 sigaction 並且 『不』使用 SA_RESTART 參數

Figure 10.10: read with timeout 1.static void 2.sig_alrm(int signo) 3.{ 4. /* nothing to do, just return to interrupt the read */ 5.} 30

lab 5 void sighandler(int signumber) { printf("get a signal named '%d', '%s'\n", signumber, sys_siglist[signumber]); if (signumber == SIGINT) exit(0); } int main(int argc, char **argv) { int sig_exist[100]; sigset_t sigset; int idx = 0; for (idx = 0; idx < 100; idx++) { if (signal(idx, sighandler) == SIG_ERR) { sig_exist[idx] = 0; } else { sig_exist[idx] = 1; } for (idx = 0; idx < 100; idx++) { if (sig_exist[idx] == 1) printf("%2d %s\n", idx, sys_siglist[idx]); } printf("my pid is %d\n", getpid()); /* 終止所有的 signal*/ sigfillset(&sigset); sigprocmask(SIG_SETMASK, &sigset, NULL); /* 睡 10 秒鐘 */ printf("sleep 10sec\n"); for(idx=0; idx<10; idx++) { sleep(1); /* 使用 write 避免 buffering*/ write(1, "*", 1); } printf("\n"); /* 重新啓動所有的 signal*/ sigemptyset(&sigset); sigprocmask(SIG_SETMASK, &sigset, NULL); while (1) { pause(); } 31

lab 5: results sleep 10sec *****^\*^\^\*^\*^\**/* 送出 5 個 ctr+\*/ get a signal named ‘3’, ‘Quit’/* 只收到一個 ctr+\*/ 32

33 sigaction Examine or modify a signal action Reliable Signals! #include int sigaction(int signo, const struct sigaction *act, struct sigaction *oact); Returns: 0 if OK, -1 on error nonnull  modify action nonnull  return action

34 sigaction 1.struct sigaction { 2./*addr of signal handler or SIG_IGN or SIG_DFL */ 3.void (*sa_handler)(int); 4./* additional signals to block */ 5.sigset_t sa_mask; 6./* signal options*/ 7.int sa_flags; 8./* alternate handler */ 9.void (*sa_sigaction)(int, siginfo_t *, void *); 10.};

35 sa_flags Check Figure for sa_flags SA_INTERRUPT (not in standard, Linux only) SA_NOCLDSTOP (POSIX.1, all 4 platforms) SA_NOCLDWAIT (XSI, all 4 platforms) SA_NODEFER (XSI, all 4 platforms) SA_ONSTACK (XSI, all 4 platforms) SA_RESETHAND (XSI, all 4 platforms) SA_RESTART (XSI, all 4 platforms) SA_SIGINFO (POSIX.1, all 4 platforms)

36 sigsetjmp, siglongjmp Similar to setjmp and longjmp Difference: saves mask and restores it #include int sigsetjmp(sigjmp_buf env, int savemask); void siglongjmp(sigjmp_buf env, int val); Returns: 0 if called directly, nonzero if returning from siglongjmp

Figure 10.20: jmp functions 1.#include 2.#include 3.#include “apue.h" 4.static void sig_usr1(int), sig_alrm(int); 5.static sigjmp_buf jmpbuf; 6.static volatile sig_atomic_t canjump; 7. 8.int main(void) { 9. if (signal(SIGUSR1, sig_usr1) == SIG_ERR) 10. err_sys("signal(SIGUSR1) error"); 11. if (signal(SIGALRM, sig_alrm) == SIG_ERR) 12. err_sys("signal(SIGALRM) error"); 13. pr_mask("starting main: "); if (sigsetjmp(jmpbuf, 1)) { 16. pr_mask("ending main: "); 17. exit(0); } 18. canjump = 1; /* now sigsetjmp() is OK */ 19. for ( ; ; ) pause(); 20.} 37 Defined by ISO C Guaranteed atomic write (1)Does not extend across page boundaries (2)Accessed with a single machine instruction (3)volatile: accessed by 2 threads: main and signal handler Defined by ISO C Guaranteed atomic write (1)Does not extend across page boundaries (2)Accessed with a single machine instruction (3)volatile: accessed by 2 threads: main and signal handler

Figure 10.20: jmp functions 1.static void sig_usr1(int signo) { 2. time_t starttime; if (canjump == 0) 5. return; /* unexpected signal, ignore */ pr_mask("starting sig_usr1: "); alarm(3); /* SIGALRM in 3 seconds */ starttime = time(NULL); 12. for ( ; ; ) * busy wait for 5 seconds */ 13. if (time(NULL) > starttime + 5) break; 14. pr_mask("finishing sig_usr1: "); canjump = 0; 17. siglongjmp(jmpbuf, 1);/* jump back to main, don't return */ 18.} 38

Time line for Figure Slides©2006 Pao-Ann Hsiung, Dept of CSIE, National Chung Cheng University, Taiwan 39 SIGUSR1 & SIGALRM

sigsuspend Function To protect critical section by blocking a signal 1.sigset_t newmask, oldmask; 2.sigemptyset(&newmask); 3.sigaddset(&newmask, SIGINT); 4.if(sigprocmask(SIG_BLOCK, &newmask, &oldmask), 0) 5. err_sys(“SIG_BLOCK error”); 6./* CRITICAL REGION OF CODE */ 7.if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0) 8. err_sys(“SIG_SETMASK error”); pause(); 40 What if signal occurs HERE?

41 sigsuspend Function Reset signal mask & put process to sleep for a signal (1 atomic operation) #include int sigsuspend(const sigset_t *sigmask); Returns: -1 with errno set to EINTR No successful return